VSCode自动补全不提示组件库深层嵌套导入路径问题
解决Vite+TypeScript组件库嵌套导入路径的VSCode自动补全问题
完善package.json的exports配置
确保嵌套图标路径的导出规则中明确指定types字段,用通配符匹配所有子路径,让TypeScript能关联到对应的类型声明文件。示例配置:"exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.es.js", "require": "./dist/index.umd.js" }, "./button": { "types": "./dist/button/index.d.ts", "import": "./dist/button/index.es.js", "require": "./dist/button/index.umd.js" }, "./icons/*": { "types": "./dist/icons/*.d.ts", "import": "./dist/icons/*.es.js", "require": "./dist/icons/*.umd.js" } }这里
./icons/*通配符会匹配@myLib/icons/status这类路径,自动映射到对应子目录的类型声明文件。确保TypeScript生成完整的嵌套类型声明
在组件库的tsconfig.json中开启类型声明生成,并覆盖所有图标子目录:{ "compilerOptions": { "declaration": true, "declarationMap": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"] }编译时会为
src/icons下的每个子模块生成独立的.d.ts文件,让TypeScript能识别到这些子路径的类型定义。优化Vite打包入口配置
用glob匹配所有模块(包括图标子目录),避免手动逐个配置入口,确保每个嵌套模块都被单独打包:import { defineConfig } from 'vite'; import path from 'path'; import glob from 'glob'; export default defineConfig({ build: { lib: { entry: Object.fromEntries( glob.sync('src/**/*.ts').map(file => [ file.replace(/^src\/(.+)\.ts$/, './$1'), path.resolve(__dirname, file) ]) ), name: 'myLib', formats: ['es', 'umd'] } } });统一图标模块的导出入口
在src/icons目录下创建index.ts,导出所有子分类的图标模块,再在根入口src/index.ts中导出整个icons模块:// src/icons/index.ts export * as status from './status'; export * as navigation from './navigation'; // 其他图标分类... // src/index.ts export * from './icons';打包后TypeScript的类型系统会自动识别
@myLib/icons下的子模块,提升自动补全的准确性。验证使用方的TypeScript配置
确保使用组件库的项目中,tsconfig.json的compilerOptions.moduleResolution设置为node16或nodenext,这是package.json的exports字段正常解析嵌套路径的必要条件。如果仍有问题,可让使用方添加路径映射:{ "compilerOptions": { "paths": { "@myLib/*": ["node_modules/@myLib/dist/*"] } } }
内容的提问来源于stack exchange,提问作者Francisco Teixeira
相关产品推荐
相关产品推荐

