Tsup发布
对比一下esm方式编写的node和ts编写的node项目2个项目
项目 | 使用额外构建工具 | 使用ts编写 | 是否需要打包 | 是否需要配置files | 调试是否麻烦 | 增加类型测试 |
---|---|---|---|---|---|---|
esm方式编写 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
ts编写 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
tsup介绍
tsup 是一个基于 ESBuild 实现在零配置的情况下快速捆绑 Typescript 模块的项目,支持 Node.js 应用中的任何内容,如:.js、.json、.mjs,及 Typescript 中的 .ts、.tsx,还包括实验性的CSS。但由于部分功能 esbuild 存在天然的不足,但又是开发者密切关注的功能,tsup 同时也选择融合其他的构建工具共同参与,这些内容会在后续的小节说明。
前端轮子哥egoist编写的。
ts转esm
在package.json里
"build": "tsup src",
"scripts": {
"tsup": {
"format": "esm",
"target": "node20",
"splitting": false,
"minify": false,
"clean": true
}
},
执行
$ npm run build
> your-first-nodejs-helloworld-with-ts@1.0.0 build
> tsup src
CLI Building entry: src/helloworld.ts, src/main.ts
CLI tsup v7.2.0
CLI Using tsup config: /Users/bytedance/workspace/npmstudy/your-first-nodejs-helloworld-with-ts/package.json
CLI Target: node20
CLI Cleaning output folder
ESM Build start
ESM dist/helloworld.js 364.00 B
ESM dist/main.js 454.00 B
ESM ⚡️ Build success in 330ms
定制npm包内容
在package.json里,修改如下。
"files": [
"dist",
"index.d.ts"
]
这样在发布的npm包里就包含dist目录和.d.ts类型定义文件了。然后执行npm publish发布即可。参见第一节。