You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从零搭建React应用出现forEach undefined报错及路由、资源加载异常问题

问题根因说明

你遇到的两个报错本质都和HtmlWebpackPlugin的工作逻辑、webpack-dev-server的内存打包特性有关:

  • 404报错是因为webpack-dev-server在开发模式下会把打包产物放在内存中,不会实际写入你配置的output.path(static/frontend)目录,你在index.html中手动写的静态脚本路径找不到对应资源。
  • 事件不触发是因为你手动改路径引入一次脚本后,HtmlWebpackPlugin还会自动向html注入一次打包脚本,重复加载React产物导致渲染、事件绑定冲突。

解决步骤

  1. 删除手动引入的脚本:删掉src/index.html里的<script src="static/frontend/main.js"></script>这一行,脚本注入完全交给HtmlWebpackPlugin自动处理。
  2. 补充webpack的publicPath配置:修改webpack.config.js的output字段,新增publicPath配置项:
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');

const htmlPlugin = new HtmlWebpackPlugin({
    template: "./src/index.html",
})

module.exports = {
    entry: ["./src/index.js"],
    output: {
        path: path.resolve(__dirname, "./static/frontend"),
        filename: "[name].js",
        publicPath: '/', // 新增这一行,保证开发、生产模式下脚本路径正确
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                },
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
        ],
    },
    resolve: {
        extensions: ['*', '.js', '.jsx'],
    },
    
    devServer: {
        port: 3000,
        historyApiFallback: true,
        contentBase: path.resolve(__dirname, "./static/frontend"), // 你之前新增的配置保留即可
      },

    plugins: [htmlPlugin]
};
  1. 验证效果:修改完成后重新执行npm run dev启动开发服务,此时不会再有404报错,路由跳转无需手动刷新,onChange、onSubmit等React事件也能正常触发。

内容的提问来源于stack exchange,提问作者rin_o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 19:36:01