Webpack构建React应用时出现多模块未找到错误求助
React + Webpack模块解析错误解决
问题详情
项目结构
- root -- app --- src ---- App.tsx ---- index.tsx --- package.json --- assets ---- styles ----- main.css --- scripts ---- webpack ----- webpack.dev.js --- public ---- index.html
构建错误
ERROR in ./src/features/app/settings/AppSettingsDetailsPage.tsx 29:0-43 Module not found: Error: Can't resolve 'src/store/store' in 'C:\Users\some\Desktop\some\some\app\src\features\app\settings'
导入代码示例
import { dispatch } from "src/store/store";
Webpack配置文件
webpack.common.js
const path = require('path'); const webpack = require('webpack'); module.exports = { target: 'web', entry: { app: './src/index.ts', }, output: { clean: true, path: path.resolve(__dirname, '../../dist'), filename: '[name].[contenthash].js', publicPath: 'dist/', }, resolve: { extensions: ['.ts', '.tsx', '.js', '.json', '.svg'], symlinks: false, }, module: { rules: [ { test: /\.html$/, exclude: /index.html/, use: [ { loader: 'html-loader', options: { sources: false, minimize: { removeComments: false, collapseWhitespace: false, }, }, }, ], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], } ], }, };
webpack.dev.js
'use strict'; const ESLintPlugin = require('eslint-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const path = require('path'); const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = (env = {}) => merge(common, { devtool: 'inline-source-map', mode: 'development', entry: "./src/index.tsx", module: { rules: [ { test: /\.tsx?$/, use: { loader: 'babel-loader', options: { cacheDirectory: true, cacheCompression: false, }, }, exclude: /node_modules/, }, ], }, plugins: [ new ESLintPlugin({ lintDirtyModulesOnly: true, extensions: ['.ts', '.tsx'], }), new MiniCssExtractPlugin({ filename: '[name].[contenthash].css', }), new HtmlWebpackPlugin({ filename: path.resolve(__dirname, '../../public/index.html'), template: path.resolve(__dirname, '../../public/index.html'), inject: false, chunksSortMode: 'none' }) ], });
解决方法
核心问题
Webpack默认不识别以src/开头的根路径导入,需要配置路径别名让它知道src对应的实际目录。
修改Webpack配置
在webpack.common.js的resolve配置里添加alias字段,映射src到项目的src目录:
resolve: { extensions: ['.ts', '.tsx', '.js', '.json', '.svg'], symlinks: false, // 新增别名配置 alias: { 'src': path.resolve(__dirname, '../src') } },
注:path.resolve(__dirname, '../src')的路径是基于webpack.common.js所在的app/scripts/webpack/目录,../src正好指向app/src/,和项目结构匹配。
补充(TypeScript用户)
如果用TypeScript开发,还要在tsconfig.json里配置路径映射,避免TS编译器报错:
{ "compilerOptions": { "baseUrl": "./", "paths": { "src/*": ["src/*"] } // 其他原有配置... } }
内容的提问来源于stack exchange,提问作者BeginnerDev
相关产品推荐
相关产品推荐

