You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"
    }
    
重新发布步骤
  1. 修改包版本号(npm不允许重复发布同一版本):执行npm version patch(或minor/major根据版本更新规则)。
  2. 重新发布:执行npm publish。

完成后,在Node项目中重新安装该包,即可看到node_modules/x目录下包含dist文件夹及编译后的JS文件。

内容的提问来源于stack exchange,提问作者Oğuz Öztınaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:05:10