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

Webpack+Babel Loader配置异常,无法处理JSX文件报Unexpected Token错误

解决React+Webpack+Babel项目中JSX的Unexpected Token错误

问题详情

运行项目时遇到如下错误:

ERROR in ./src/index.js 10:12
Module parse failed: Unexpected token (10:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
| const root = createRoot(domNode);
| 
 root.render(<App />);

已尝试重装依赖、清除缓存,问题仍未解决。环境信息:Node.js 20.12.1,MacOS。

排查与修复步骤

1. 移除Webpack配置中重复的HtmlWebpackPlugin模板项

你的Webpack配置里HtmlWebpackPlugin重复定义了template属性,后一项会覆盖前一项,虽非直接错误原因,但会导致配置混乱。修改为单一有效路径:

plugins: [
    new HtmlWebpackPlugin({
        template: './public/index.html' // 保留唯一的template配置
    }),
],

2. 单独配置Babel(替代Webpack内联配置)

将Babel预设配置从Webpack的babel-loader选项中移出,在项目根目录创建.babelrc文件,确保Babel配置被正确加载:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

同时简化Webpack中babel-loader的配置:

{
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    use: 'babel-loader' // 无需在Webpack内重复写presets
},

3. 调整Webpack的扩展名解析顺序

将.jsx放在resolve.extensions的首位,确保Webpack优先识别JSX文件:

resolve: {
    extensions: ['.jsx', '.js'],
},

4. 彻底清理依赖并重新构建

执行以下命令完全重置依赖环境:

rm -rf node_modules package-lock.json
npm install
npm start

修复后的完整配置示例

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        clean: true // 自动清空dist目录
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html'
        }),
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    resolve: {
        extensions: ['.jsx', '.js'],
    },
    devServer: {
        static: {
            directory: path.join(__dirname, 'public'),
        },
        port: 3000,
        hot: true // 开启热更新
    },
};

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:29:53