如何从多个TypeScript文件构建单个ES6模块 [英] How to build a single ES6 module from several TypeScript files

查看:833
本文介绍了如何从多个TypeScript文件构建单个ES6模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:

  // a.ts 
函数a(){}

// b.ts
函数b(){}

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

我需要构建一个仅导出 myLib 的UMD模块(即一个JavaScript文件)作为默认导出。 / p>

我看到两个选项。第一个:


  1. 运行 tsc 将每个文件编译成JavaScript; li>
  2. 将所有生成的JS文件连接到一个文件中 my-lib.js ;

  3. 并附加UMD所需的代码。

第二个:


  1. 将所有TypeScript文件连接到一个文件中 my-lib.ts ;

  2. 追加导出: export default myLib ;

  3. 在连接文件上运行 tsc li>

这两个选项都是丑陋的,并且松动了地图文件。



有更好的方法吗?

解决方案

正确的方法是创建一个桶文件将重新导出模块。

  // foo / a.ts 
导出功能a(){}

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

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

然后在您的消费者中:

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

a();
b();


The code of my 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 UMD 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. Prepend and append the code needed by UMD.

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?

解决方案

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();

这篇关于如何从多个TypeScript文件构建单个ES6模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆