NX生成的TypeScript库package.json中main字段指向错误的解决方法
问题描述
我通过以下步骤创建了NX工作区与TypeScript库:
- 使用命令创建Angular预设的NX工作区:
npx create-nx-workspace --name libtest --preset angular --style scss --appName demo --nxCloud false code libtest - 添加@nrwl/node并生成可构建、可发布的TypeScript库:
nx add @nrwl/node nx generate @nrwl/js:library --name=example-qr-code --buildable --publishable --import-path @example/qr-code - 更新NX到最新版本并完成迁移。在工作区内的Angular应用中可正常使用该库,但在外部新Angular项目中引用时出现模块找不到的错误:
./node_modules/@example/ng-qr-code/fesm2020/example-ng-qr-code.mjs:6:0-53 - Error: Module not found: Error: Can't resolve '@example/qr-code' in 'C:\repos\qrtest\node_modules@example\ng-qr-code\fesm2020'
手动修改该库node_modules中的package.json,将main字段从./src/index.ts改为./src/index.js后问题解决。请问如何让NX自动生成main字段指向js文件的package.json?
解决方案
1. 遵循正确的发布流程:发布构建产物而非源文件
NX生成的可发布库,必须先完成构建再发布产物目录,而非直接发布源文件目录:
# 构建库到dist目录 nx build example-qr-code # 进入构建产物目录 cd dist/libs/example-qr-code # 执行npm发布 npm publish
构建后的产物目录中,package.json的main字段会自动指向编译后的index.js文件,而非源文件index.ts。
2. 调整库的构建配置
打开库根目录下的project.json(路径:libs/example-qr-code/project.json),检查build目标的配置是否正确:
"targets": { "build": { "executor": "@nrwl/js:tsc", "outputs": ["{options.outputPath}"], "options": { "outputPath": "dist/libs/example-qr-code", "main": "libs/example-qr-code/src/index.ts", "tsConfig": "libs/example-qr-code/tsconfig.lib.json", "assets": ["libs/example-qr-code/*.md"], "packageJson": "libs/example-qr-code/package.json" } } }
outputPath确保产物输出到dist目录,与源文件分离packageJson指定使用库目录下的package.json作为模板,NX构建时会自动替换路径为编译后的JS文件路径
3. 自定义库的package.json模板
直接修改库目录下的package.json(路径:libs/example-qr-code/package.json),明确指定main字段为构建后的JS路径:
{ "name": "@example/qr-code", "version": "0.0.1", "main": "./index.js", "typings": "./index.d.ts", "publishConfig": { "access": "public" } }
NX在构建时会基于该模板生成产物目录中的package.json,确保main字段始终指向正确的JS文件。
4. 重新同步NX配置
如果是版本更新后出现的配置偏差,重新执行迁移命令确保所有配置同步到最新规范:
nx migrate latest nx migrate --run-migrations
内容的提问来源于stack exchange,提问作者Pieterjan
相关产品推荐
相关产品推荐

