ncc将 Node.js 项目编译为单个文件

联合创作 · 2023-09-23 15:47

ncc 是一个简单的 CLI,可以将 Node.js 项目编译为单个文件,包括项目的依赖与 gcc-style。


功能



  • 将最小包发布到npm

  • 仅将相关应用程序代码发送到无服务器环境(云函数)

  • 不用浪费时间配置捆绑包

  • 通常启动时间更短,I / O开销更少

  • 编译语言的体验(如:go


设计目标



  • 零配置

  • TypeScript 支持

  • 仅支持 Node.js 程序作为输入/输出

  • 支持所有 Node.js 模式和 npm 模块


用法


安装




npm i -g @zeit/ncc


用法




$ ncc build input.js -o dist


输出的Node.js的身体结实input.jsdist/index.js


执行测试


对于测试和调试,可以将文件构建到临时目录中,并使用以下命令执行完整的源映射支持:




$ ncc run input.js


使用TypeScript


唯一的要求是指ncc.ts.tsx文件。一个tsconfig.json 文件是必要的。您很可能希望表明es2015支持:




{
"compilerOptions": {
"target": "es2015",
"moduleResolution": "node"
}
}


以编程方式从Node.js




require('@zeit/ncc')('/path/to/input', {
// provide a custom cache path or disable caching
cache: "./custom/cache/path" | false,
// externals to leave as requires of the build
externals: ["externalpackage"],
minify: false, // default
sourceMap: false, // default
sourceMapBasePrefix: '../' // default treats sources as output-relative
// when outputting a sourcemap, automatically include
// source-map-support in the output file (increases output by 32kB).
sourceMapRegister: true, // default
watch: false, // default
v8cache: false, // default
quiet: false, // default
debugLog = false // default
}).then(({ code, map, assets }) => {
console.log(code);
// Assets is an object of asset file names to { source, permissions, symlinks }
// expected relative to the output code (if any)
})


watch: true设置,构建产物不是一个promise,但具有以下特征:




{
// handler re-run on each build completion
// watch errors are reported on "err"
handler (({ err, code, map, assets }) => { ... })
// handler re-run on each rebuild start
rebuild (() => {})
// close the watcher
void close ();
}

浏览 23
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报