React项目Webpack路径解析错误:无法解析src开头的模块导入
解决Webpack无法解析src开头的绝对路径导入问题
我在React项目中使用webpack ^5.74.0版本,执行npm start时,webpack抛出模块未找到错误,无法解析像src/content/Login/LoginAuthentication这类以src开头的路径模块,但使用../../folder1/filename这类相对路径导入时一切正常。项目里这类导入语句太多,没法逐一修改,附上webpack配置文件求解决方法。
报错信息
ERROR in ./src/layouts/SidebarLayout/Sidebar/SidebarMenu/items.ts 21:0-83 Module not found: Error: Can't resolve 'src/content/Login/LoginAuthentication' in 'E:\project\src\layouts\SidebarLayout\Sidebar\SidebarMenu' @ ./src/layouts/SidebarLayout/Sidebar/SidebarMenu/index.tsx 7:0-32 77:14-27 @ ./src/layouts/SidebarLayout/Sidebar/index.tsx 10:0-40 40:32-43 56:34-45 @ ./src/layouts/SidebarLayout/index.tsx 7:0-32 24:33-40 @ ./src/router/PrivateRoute.tsx 11:0-53 135:29-42 148:29-42 167:29-42 234:29-42 259:29-42 @ ./src/router/index.tsx 4:0-42 5:13-25 @ ./src/App.tsx 5:0-30 17:33-39 @ ./src/index.tsx 4:0-24 18:36-39
当前webpack配置文件
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const DirectoryNamedWebpackPlugin = require("directory-named-webpack-plugin"); module.exports={ entry:path.resolve(__dirname,'..','./src/index.tsx'), resolve:{ extensions:['.tsx','.ts','.js'] }, module:{ rules:[{ test:/\.(ts|js)x?$/, exclude:/node_modules/, use:[ { loader:'babel-loader' } ] },{ test:/\.(sass|css|scss)$/, use:['style-loader','css-loader'] }, { test: /\.(png|svg|jpg|jpeg|gif)/, type: 'asset/resource' },{ test: /\.(png|svg|jpg|jpeg|gif)/, type: 'asset/inline' } // ,{ // test: /\.(png|svg|jpg|jpeg|gif|ico)$/, // exclude: /node_modules/, // use: ['file-loader?name=[name].[ext]'] // ?name=[name].[ext] is only necessary to preserve the original file name // } ] }, output:{ path:path.resolve(__dirname,'..','./dist'), filename:'bundle.js' }, plugins:[new HtmlWebpackPlugin({ template:path.resolve(__dirname,'..','./public/index.html') }) ] }
解决方案
1. 配置Webpack的路径别名
在webpack配置的resolve字段中添加alias,将src映射到项目根目录下的src文件夹:
resolve:{ extensions:['.tsx','.ts','.js'], alias: { 'src': path.resolve(__dirname, '..', './src') } },
修改后,Webpack解析src/xxx这类路径时会自动指向项目src目录下的对应文件,无需修改现有导入语句。
2. (可选)配置TypeScript路径映射(如果用了TS)
若项目使用TypeScript,需在tsconfig.json中添加baseUrl和paths,让TS编译器识别这类路径,避免编辑器报错:
{ "compilerOptions": { "baseUrl": "./", "paths": { "src/*": ["src/*"] } // 其他原有配置... } }
内容的提问来源于stack exchange,提问作者ajith kumar
相关产品推荐
相关产品推荐

