TypeScript编写的NPM包发布后未编译,如何正确发布安装?
问题描述
我使用TypeScript创建了一个简单的控制台日志包,代码如下:
src/index.ts
console.log('Hello, World!')
package.json
{ "name": "x", "version": "1.0.0", "description": "", "main": "dist/index.js", "scripts": { "build": "tsc", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "typescript": "^4.9.5" } }
tsconfig.json
{ "compilerOptions": { "target": "es6", "module": "commonjs", "declaration": true, "outDir": "dist", "strict": true, "esModuleInterop": true }, "include": ["src/**/*"], "exclude": ["node_modules", "**/*.test.ts"] }
我已执行npm publish将包发布至npmjs.com,但在Node项目中安装此包后,进入node_modules查看发现仅存在TS文件,未编译为JS文件。请问如何正确发布或安装该包?
解决方案
发布前先执行编译命令:你当前直接执行
npm publish但未先编译TypeScript代码,导致dist目录(编译产物目录)未生成或未被包含到发布包中。发布前必须先运行npm run build,确保dist目录生成编译后的JS文件和声明文件。配置
package.json的files字段:手动指定需要发布的文件,确保dist目录被包含。修改package.json添加以下内容:"files": [ "dist/**/*" ]若需要同时发布TS源码,可额外添加
"src/**/*"。检查
.gitignore配置:如果你的.gitignore文件中包含dist/,会导致npm发布时忽略该目录,需移除或调整这条规则,确保dist目录能被正常发布。添加
prepare脚本自动编译:在package.json的scripts中添加prepare脚本,这样执行npm publish或他人安装你的包时会自动触发编译,避免遗漏步骤:"scripts": { "build": "tsc", "prepare": "npm run build", "test": "echo \"Error: no test specified\" && exit 1" }
重新发布步骤
- 修改包版本号(npm不允许重复发布同一版本):执行
npm version patch(或minor/major根据版本更新规则)。 - 重新发布:执行
npm publish。
完成后,在Node项目中重新安装该包,即可看到node_modules/x目录下包含dist文件夹及编译后的JS文件。
内容的提问来源于stack exchange,提问作者Oğuz Öztınaz
相关产品推荐
相关产品推荐

