配置tsconfig的paths后出现模块找不到的问题
问题原因
VS Code能识别@components/*这类路径是因为它读取了tsconfig.json里的paths配置,但React的构建工具(比如Webpack、Vite)不会自动读取tsconfig的paths规则,所以编译时会出现模块找不到的错误。
解决方案
根据你使用的构建工具,对应配置别名:
1. 如果你用的是Create React App(CRA)
CRA默认不允许直接修改Webpack配置,需要借助第三方工具:
- 安装
craco:npm install @craco/craco --save-dev - 在项目根目录创建
craco.config.js,添加别名配置:const path = require('path'); module.exports = { webpack: { alias: { '@components': path.resolve(__dirname, 'src/core/components/'), '@type': path.resolve(__dirname, 'src/types/') } } }; - 修改
package.json里的启动脚本:"scripts": { "start": "craco start", "build": "craco build", "test": "craco test" }
2. 自定义Webpack配置
如果是自己配置的Webpack项目,直接修改webpack.config.js的resolve.alias:
const path = require('path'); module.exports = { // 其他配置 resolve: { alias: { '@components': path.resolve(__dirname, 'src/core/components/'), '@type': path.resolve(__dirname, 'src/types/') }, extensions: ['.ts', '.tsx', '.js', '.jsx'] // 需添加TS相关扩展名 } };
3. Vite项目
如果用Vite构建,修改vite.config.ts:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; export default defineConfig({ plugins: [react()], resolve: { alias: { '@components': path.resolve(__dirname, './src/core/components'), '@type': path.resolve(__dirname, './src/types') } } });
最后重启开发服务器,问题即可解决。
内容的提问来源于stack exchange,提问作者great programmer
相关产品推荐
相关产品推荐

