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

posted on   荣锋亮  阅读(4464)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-05-16 cube.js schema 存储的几种推荐模式说明
2021-05-16 apostrophe 基于Nunjucks+mongo 的cms 系统
2021-05-16 tera rust 的jinja2 模版引擎
2021-05-16 liquidjs 兼容shopify liquid 的纯js 模板引擎
2021-05-16 tus 参考断点续传协议
2020-05-16 ruby 一些不错的性能分析工具
2020-05-16 How to Fix Slow Code in Ruby

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示