javascripttypescriptumd

Building a Typescript project to UMD but getting multiple files


I want to compile my index.ts:

import { initContainer } from "./embedTypes/container";
import { initPopup } from "./embedTypes/popup";
import { initBubble } from "./embedTypes/chat";

const Typebot = {
  initContainer,
  initPopup,
  initBubble,
};

export default Typebot;

to a UMD index.js so that I can call it with a <script> tag. Here is my ts configuration:

{
  "compilerOptions": {
    "outDir": "dist",
    "declaration": true,
    "module": "UMD",
    "target": "ES6",
    "moduleResolution": "node",
    "strict": true
  },
  "include": ["src/**/*.ts", "tests/**/*.ts"]
}

And here is what it compiles (index.js):

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "./embedTypes/container", "./embedTypes/popup", "./embedTypes/chat"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const container_1 = require("./embedTypes/container");
    const popup_1 = require("./embedTypes/popup");
    const chat_1 = require("./embedTypes/chat");
    const Typebot = {
        initContainer: container_1.initContainer,
        initPopup: popup_1.initPopup,
        initBubble: chat_1.initBubble,
    };
    exports.default = Typebot;
});

It looks like this isn't right, it should build a unique index.js but here it compiles to multiple files.

What am I missing?


Solution

  • TS compiler is not a bundler, it will just compile each file independently. I would recommend using Webpack for it's all-around goodness and easy to use, unless you want to jump right into using a framework like Angular or React, which give you this out-of-the-box. Other options could include browserify, grunt, gulp, babel, parcel, ...