求助:导入Azure Artifacts发布的Node库时遇模块及类型声明错误
解决TypeScript包导入报错:Cannot find module或类型声明缺失
问题根源
你发布的是未编译的TypeScript源码,且缺少类型声明入口配置,导致React项目无法识别模块结构和类型信息。
具体修复步骤
1. 添加TypeScript编译配置
在包项目根目录创建tsconfig.json,配置编译规则和输出:
{ "compilerOptions": { "target": "ES6", "module": "ESNext", "declaration": true, // 自动生成类型声明文件(.d.ts) "outDir": "./dist", // 编译产物输出目录 "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["*.ts", "*.tsx"], // 匹配你的源码文件路径,若有src目录则改为["src/**/*"] "exclude": ["node_modules", "dist"] }
2. 更新package.json关键配置
修改package.json,指向编译后的产物,同时指定类型入口:
{ "name": "@test/helloworld", "version": "1.0.0", "description": "just a test", "main": "dist/index.js", // 编译后的JS入口文件 "types": "dist/index.d.ts", // 类型声明文件入口 "files": ["dist"], // 仅发布编译产物目录,避免冗余文件 "scripts": { "build": "tsc", // 添加编译命令 "test": "echo \"Error: no test specified\" && exit 1" }, // ... 其他依赖字段不变 }
3. 编译并重新发布
先执行编译生成产物:
npm run build
确认dist目录生成后,重新发布到Azure Artifacts:
npm publish
4. 在React项目中重新验证
卸载旧包并重新安装:
npm uninstall @test/helloworld npm install @test/helloworld@1.0.0
之后再尝试导入使用:
import { HelloWorld } from '@test/helloworld';
额外提示
- 若使用Rollup打包,需确保配置文件输出
dist目录的JS和类型文件,避免编译产物缺失。 - 检查Azure Artifacts中的包内容,确认
dist目录已正确上传。
内容的提问来源于stack exchange,提问作者Bridgette Ryan
相关产品推荐
相关产品推荐

