如何让Webpack中正常运行的本地模块app-interfaces适配Vite
问题解决步骤
原理说明
原有基于react-scripts的项目可以正常识别app-interfaces模块,是因为create-react-app默认的TypeScript配置会自动包含src目录下所有.d.ts类型声明文件。你在Interfaces.d.ts中写的declare module 'app-interfaces'属于全局模块声明,只要TypeScript编译时能加载到这个文件,就可以识别对应的模块导入,不需要显式引用文件路径,也不需要额外的Webpack配置。
具体配置
第一步:修改tsconfig.json配置
这一步是为了让TypeScript正常识别该模块,解决TS2307报错,二选一配置即可:
- 方案1:确保
include字段覆盖声明文件路径
检查项目根目录的tsconfig.json,确认include数组包含src目录下的所有文件,或者直接精准添加声明文件路径:{ "include": [ "src/**/*", "src/bin/models/Interfaces.d.ts" ] } - 方案2:添加paths路径映射
如果方案1不生效,可以在compilerOptions中添加路径映射明确模块指向:{ "compilerOptions": { "baseUrl": ".", "paths": { "app-interfaces": ["src/bin/models/Interfaces.d.ts"] } } }
第二步:(可选)添加Vite运行时别名
如果你的app-interfaces后续会包含实际运行的业务代码,而非纯类型声明,需要在vite.config.ts中同步配置别名,避免运行时报错:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], resolve: { alias: { 'app-interfaces': path.resolve(__dirname, 'src/bin/models/Interfaces.d.ts') } } })
配置完成后重启TS服务和Vite开发服务即可生效,不需要修改现有业务代码的导入语句。
内容的提问来源于stack exchange,提问作者oligofren
相关产品推荐
相关产品推荐

