Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

ecmascript 6 - 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.

Example:

// a.ts
function a() {}

// b.ts
function b() {}

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

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

I see two options. The first one:

  1. Run tsc to compile each file to JavaScript;
  2. Concatenate all the generated JS files into a single file my-lib.js;
  3. Append the code needed by ES6 (export …).

The second one:

  1. Concatenate all the TypeScript files into a single file my-lib.ts;
  2. Append the export: export default myLib;
  3. Run tsc on the concatenated file.

Both options are ugly and loose the map file.

Is there a better way to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct way is to create a barrel file that will re export the modules.

// foo/a.ts
export function a() {}

// foo/b.ts
export function b() {}

// foo/index.ts
export {a} from './a';
export {b} from './b';

Then in your consumer:

import {a, b} from './foo';

a();
b();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...