如何从多个TypeScript文件构建单个ES6模块(用于前端库) [英] 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
}
我需要构建一个仅导出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:
- 运行
tsc
将每个文件编译为JavaScript; - 将所有生成的JS文件连接为一个文件
my-lib.js
; - 附加ES6(
export …
)所需的代码.
- Run
tsc
to compile each file to JavaScript; - Concatenate all the generated JS files into a single file
my-lib.js
; - Append the code needed by ES6 (
export …
).
第二个:
- 将所有TypeScript文件连接到一个文件中
my-lib.ts
; - 追加导出:
export default myLib
; - 在连接的文件上运行
tsc
.
- Concatenate all the TypeScript files into a single file
my-lib.ts
; - Append the export:
export default myLib
; - Run
tsc
on the concatenated file.
这两个选项都很丑陋,导致map
文件丢失.
Both options are ugly and loose the map
file.
有更好的方法吗?
推荐答案
我添加了一个答案,因为今天前端库的正确方法是使用 首先,编写ES6模块import
和export
:
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 };
另请参阅:
- 汇总REPL: https://rollupjs.org/repl
- 文章: Webpack和汇总:相同但不同
注意:权威解决方案用于构建定义文件(.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屋!