动态路由页面刷新时Webpack报错,如何配置绝对路径?
问题
在使用React Router + Webpack的项目中,刷新动态路由页面时出现以下错误:
Refused to execute script from 'http://localhost:3000/history/bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
实际bundle.js存放在项目根目录而非history目录,问题出在Webpack默认使用相对路径查找资源,导致动态路由下找不到正确的bundle文件。需要配置绝对路径来解决,当前Webpack配置如下:
module.exports = { mode: 'development', resolve: { extensions: ['.ts', '.tsx', '.js'], }, entry: { bundle: path.resolve(__dirname, 'src/index.tsx'), }, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js', clean: true, assetModuleFilename: '[name][ext]', }, devServer: { static: { directory: path.resolve(__dirname, 'build'), }, port: 3000, open: true, hot: true, historyApiFallback: true, }, module: { rules: [ { test: /\.tsx?/, use: 'babel-loader', }, { test: /\.scss/, use: ['style-loader', 'css-loader', 'sass-loader'], }, { test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource', }, ], }, plugins: [ new HtmlPlugin({ template: path.resolve(__dirname, 'public/index.html'), }), new RefresherPlugin(), ], };
解决方案
只需在Webpack配置的output对象中添加publicPath: '/',强制所有资源从根路径加载,这样不管当前处于哪个路由层级,都会正确请求http://localhost:3000/bundle.js而非相对路径下的文件。
修改后的完整配置如下(突出修改部分):
module.exports = { mode: 'development', resolve: { extensions: ['.ts', '.tsx', '.js'], }, entry: { bundle: path.resolve(__dirname, 'src/index.tsx'), }, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js', clean: true, assetModuleFilename: '[name][ext]', // 添加这一行,指定绝对根路径 publicPath: '/' }, devServer: { static: { directory: path.resolve(__dirname, 'build'), }, port: 3000, open: true, hot: true, historyApiFallback: true, }, module: { rules: [ { test: /\.tsx?/, use: 'babel-loader', }, { test: /\.scss/, use: ['style-loader', 'css-loader', 'sass-loader'], }, { test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource', }, ], }, plugins: [ new HtmlPlugin({ template: path.resolve(__dirname, 'public/index.html'), }), new RefresherPlugin(), ], };
publicPath指定了Webpack输出资源的基础URL,设置为/后,所有生成的资源引用都会以根路径开头,避免了动态路由下相对路径解析错误的问题。配合你已开启的historyApiFallback: true,就能完美解决刷新动态路由时的资源加载异常。
内容的提问来源于stack exchange,提问作者Pav
相关产品推荐
相关产品推荐

