Angular 15:VS Code无法自动推荐私有库导入问题求助
解决VS Code无法自动提示私有库子入口导入的问题
配置库的package.json子入口与类型映射
在你的私有库的package.json中,必须明确配置exports字段,为每个子入口指定对应的编译产物和类型文件,同时补充typesVersions兼容旧版TypeScript解析:{ "name": "@company/lib", "exports": { "./subentry1": { "import": "./dist/subentry1/index.js", "require": "./dist/subentry1/index.cjs", "types": "./dist/subentry1/index.d.ts" }, "./subentry2": { "import": "./dist/subentry2/index.js", "require": "./dist/subentry2/index.cjs", "types": "./dist/subentry2/index.d.ts" } }, "typesVersions": { "*": { "subentry1": ["./dist/subentry1/index.d.ts"], "subentry2": ["./dist/subentry2/index.d.ts"] } } }注意:
types字段必须准确指向子入口对应的.d.ts文件,否则VS Code无法识别类型信息。确保库生成完整的类型声明文件
如果你的库用TypeScript编写,在库的tsconfig.json中开启以下配置,确保构建时生成正确的类型文件:{ "compilerOptions": { "declaration": true, "declarationMap": true, "outDir": "./dist" } }构建后检查
dist目录下的每个子入口是否都有对应的.d.ts和.d.ts.map文件。调整项目的TypeScript配置
在使用该库的项目的tsconfig.json中,确保moduleResolution设置为node16或nodenext,这两个模式支持package.json的exports字段解析:{ "compilerOptions": { "moduleResolution": "node16", "module": "ESNext" } }若使用的TypeScript版本低于4.7,可通过
paths字段手动映射子入口路径:{ "compilerOptions": { "paths": { "@company/lib/subentry1": ["node_modules/@company/lib/dist/subentry1/index.d.ts"], "@company/lib/subentry2": ["node_modules/@company/lib/dist/subentry2/index.d.ts"] } } }重启VS Code的TypeScript服务
按Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac),输入TypeScript: Restart TS Server,重启语言服务后,VS Code会重新加载库的类型信息。清除缓存(可选)
如果以上步骤无效,可尝试删除项目根目录的.vscode文件夹,或重启VS Code,清除旧的类型缓存。
内容的提问来源于stack exchange,提问作者ertucode
相关产品推荐
相关产品推荐

