如何从多个TypeScript文件构建单个ES6模块(用于前端库) [英] How to build a single ES6 module from several TypeScript files (for a frontend library)

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

问题描述

我的前端库的代码分为几个源文件.

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
}

我需要构建一个仅导出myLib作为默认导出的ES6模块(即,一个JavaScript文件).

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. 运行tsc将每个文件编译为JavaScript;
  2. 将所有生成的JS文件连接为一个文件my-lib.js;
  3. 附加ES6(export …)所需的代码.
  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 …).

第二个:

  1. 将所有TypeScript文件连接到一个文件中my-lib.ts;
  2. 追加导出:export default myLib;
  3. 在连接的文件上运行tsc.
  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.

这两个选项都很丑陋,导致map文件丢失.

Both options are ugly and loose the map file.

有更好的方法吗?

推荐答案

我添加了一个答案,因为今天前端库的正确方法是使用 首先,编写ES6模块importexport:

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"

然后,使用tsc并将代码module设置为"es6",将代码编译为JavaScript.

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

然后,让Rollup从JavaScript代码构建一个扁平捆绑包.对于上面的代码,Rollup生成了这个捆绑包:

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 };

另请参阅:

注意:权威解决方案用于构建定义文件(.d.ts)尚未实现(2018年3月). 我仍然串联文件并使用Node.js脚本在单个TypeScript定义文件中生成导出的类型.

Notice: The definitive solution to build the definition file (.d.ts) is not implemented yet (March, 2018). I still concatenate files with a Node.js script to generate exported types in a single TypeScript definition file.

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

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