我在我的项目中使用 React Router + Webpack。当我尝试在动态路由上刷新页面时,它会抛出此错误:
拒绝执行来自 'http://localhost:3000/history/bundle.js' 的脚本,因为它的 MIME 类型('text/html')不可执行,并且启用了严格的 MIME 类型检查。
请注意,bundle.js 存在于项目的根目录中,而不是历史记录,因此是错误。问题显然出在 Webpack 配置中。它在相对目录中搜索 bundle,而 ofc 在动态路径上找不到。但是如何指定绝对路径呢?我玩了一下,但不能把手指放在上面。这是配置:
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.config.js 文件的输出部分添加
publicPath
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].js',
publicPath: '/',
clean: true,
assetModuleFilename: '[name][ext]',
}