启动webpack-dev-server后,可以直接进入静态路由(如
http://localhost:3456/one
),但不能直接进入动态路由(如http://localhost:3456/two/1234
)
我相信我的 webpack-dev-server 配置中遗漏了一些东西,但不确定是什么。
浏览器控制台输出这个错误:
GET http://localhost:3456/two/dev-bundle.js 404 (Not Found)
Refused to execute script from 'http://localhost:3456/two/dev-bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
webpack.config.js
const path = require("path")
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack")
module.exports = {
mode: "development",
devtool: "eval-source-map",
entry: [
"./index.js",
],
output: {
filename: "dev-bundle.js",
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "dev.html")
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
historyApiFallback: true,
hot: true,
port: 3456,
stats: "minimal"
}
}
app.js
import React, { Component } from "react"
import { hot } from "react-hot-loader"
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"
import ComponentOne from "./components/ComponentOne"
import ComponentTwo from "./components/ComponentTwo"
const MyApp = () => (
<div>
<Router>
<Switch>
<Route exact path="/" component={ComponentOne} />
<Route exact path="/one" component={ComponentOne} />
<Route path="/two/:id" component={ComponentTwo} />
</Switch>
</Router>
</div>
)
export default hot(module)(MyApp)
ComponentTwo.js
import React, { Component } from "react"
import { Link } from "react-router-dom"
export default class ComponentTwo extends Component {
render() {
return (
<div>
<h1>ComponentTwo for {this.props.match.params.id}</h1>
</div>
)
}
}
任何帮助表示赞赏。
我能够通过更新部分 webpack 配置来解决这个问题:
output: {
filename: "dev-bundle.js",
publicPath: "/", // added this line
},
控制台错误仍然存在,但至少页面已加载。
使用 webpack 5,当你像我展示的那样设置你的配置文件时,404 错误将消失。
output: { publicPath: "/", },
我觉得第一个答案一定要和解法一样选