1. 程式人生 > 其它 >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