编程语言
首页 > 编程语言> > nodejs 几个方便的打包工具

nodejs 几个方便的打包工具

作者:互联网

vercel 提供了好几个方便的nodejs 打包工具,pkg 以及ncc

pkg 使用场景

pkg 可以保证nodejs 可以直接打包到一个二进制文件中,我们可以直接运行就不直接依赖外部nodejs了

ncc 使用场景

ncc 可以将nodejs 应用打包为一个单一文件,好处很明显,就是我们不需要使用npm 包安装以及分发很多文件了,直接一个文件就可以搞定了
比如适合类似serverless 以及需要单一文件入口运行的,特别类似java 的fat jar,支持ts,二进制addon 以及动态require

参考使用

工具使用都比较简单,pkg 的以前介绍过,主要介绍下ncc 的

 
{
  "name": "first",
  "version": "1.0.0",
  "main": "lib/app.js",
  "types": "lib/app.d.ts",
  "license": "MIT",
  "devDependencies": {
    "@types/node": "^17.0.33",
    "@types/shortid": "^0.0.29",
    "@vercel/ncc": "^0.33.4",
    "typescript": "^4.6.4"
  },
  "scripts": {
    "build": "tsc",
    "rollup":"yarn  build && ncc build lib/index.js -o dist"
  },
  "dependencies": {
    "shortid": "^2.2.16"
  }
}

ts 配置

{
  "include": [
    "src/**/*"
  ],
  "compilerOptions": {
    "outDir": "lib",
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

src/index.ts

import shortid = require("shortid")
console.log(shortid.generate())

构建效果

 

 


直接运行ts 项目(效果是一样的)

 
ncc build src/index.ts -o app 

参考资料

https://github.com/vercel/pkg
https://github.com/vercel/ncc
https://www.cnblogs.com/rongfengliang/p/10329403.html
https://github.com/vercel/ncc/blob/main/package-support.md

标签:nodejs,ts,shortid,pkg,方便,ncc,com,打包,vercel
来源: https://www.cnblogs.com/rongfengliang/p/16276567.html