Paleo Paleo - 3 years ago 218
TypeScript Question

How to build a single ES6 module from several TypeScript files (for a frontend library)

The code of my frontend library is split into several source files.


// a.ts
function a() {}

// b.ts
function b() {}

// main.ts
const myLib = {
a: a,
b: b

I need to build one UMD module (ie. one JavaScript file) that exports only
, as the default export.

I see two options. The first one:

  1. Run
    to compile each file to JavaScript;

  2. Concatenate all the generated JS files into a single file

  3. Prepend and append the code needed by UMD.

The second one:

  1. Concatenate all the TypeScript files into a single file

  2. Append the export:
    export default myLib

  3. Run
    on the concatenated file.

Both options are ugly and loose the

Is there a better way to do that?

Answer Source

I add an answer because today the correct way for a frontend library is to use Rollup.

First, write ES6 modules, import and export them:

// file-a.ts
export function a() {}

// file-b.ts
export function b() {}

// main.ts
export { a } from "./file-a"
export { b } from "./file-b"

Then, compile the code to JavaScript with the option module set to "es6".

Then, let Rollup build a flat bundle from the JavaScript code. For the code above, Rollup generates this bundle:

function a() {}
function b() {}
export { a, b };

See also:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download