如何配置TypeScript移除类型文件中的模块文件夹前缀?
组件库类型声明模块名称不匹配问题
项目与构建背景
项目结构:
src/ button/ j-button.ts j-button.test.ts
经Vite构建后输出目录:
dist/ j-button.js
组件库package.json中类型声明配置:
"types": "index.d.ts"
当前通过tsc --outFile index.d.ts生成的index.d.ts内容片段:
declare module "button/j-button" { ... }
问题表现
消费应用中使用的导入语句为:
import JButton from '@jump/components/dist/j-button'
由于生成的类型声明模块名称为"button/j-button",与实际导入路径不匹配,导致TypeScript无法识别对应类型,类型提示失效。
解决方案
方法1:调整TypeScript配置生成匹配路径的声明文件
在组件库的tsconfig.json中配置路径映射与输出目录,让TS直接生成对应构建路径的类型声明:
{ "compilerOptions": { "baseUrl": ".", "paths": { "@jump/components/dist/*": ["src/*"] }, "declaration": true, "declarationDir": "./dist", "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"], "exclude": ["**/*.test.ts"] }
执行tsc后,dist目录会生成j-button.d.ts,随后修改package.json的types字段:
"types": "dist/j-button.d.ts"
若有多组件,可在dist下创建index.d.ts统一导出所有组件类型,再将types指向该文件。
方法2:脚本替换生成后的模块名称
编写简单Node脚本,在TS生成声明文件后替换模块名称:
const fs = require('fs'); const filePath = './index.d.ts'; const content = fs.readFileSync(filePath, 'utf8'); // 替换为实际导入的模块名称 const updatedContent = content.replace(/declare module "button\/j-button"/g, 'declare module "@jump/components/dist/j-button"'); fs.writeFileSync(filePath, updatedContent);
在package.json的scripts中添加执行命令:
"scripts": { "build:types": "tsc --outFile index.d.ts && node fix-types.js" }
方法3:使用Vite插件自动生成正确类型
借助vite-plugin-dts插件,它会匹配Vite的构建输出自动生成对应类型声明:
- 安装依赖:
npm install vite-plugin-dts --save-dev
- 配置
vite.config.ts:
import { defineConfig } from 'vite'; import dts from 'vite-plugin-dts'; export default defineConfig({ plugins: [ dts({ outputDir: './dist', staticImport: true }) ], build: { lib: { entry: './src/button/j-button.ts', fileName: 'j-button' } } });
执行vite build后,dist目录会生成j-button.d.ts,最后将package.json的types字段指向该文件即可。
内容的提问来源于stack exchange,提问作者atomkirk
相关产品推荐
相关产品推荐

