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

React项目index.js模块解析失败报错的解决方法咨询

Fixing Module Parse Error with JSX in React + Webpack Project

Let's break down the issues causing this error and fix them step by step:

1. Resolve Babel Dependency Mismatch

You're using outdated Babel 6 packages, but your .babelrc is configured for Babel 7. This mismatch prevents proper transpilation of JSX. Let's clean up and install the correct packages:

First, uninstall the old Babel-related packages:

npm uninstall babel-cli babel-preset-es2015 babel-preset-react babel-preset-stage-2 babel-preset-env babelify browserify

Then install the Babel 7 dependencies and missing Webpack tools:

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader @babel/plugin-proposal-class-properties html-webpack-plugin webpack-dev-server

2. Fix Webpack Configuration Errors

Your webpack.config.js has two critical issues in the JS loader rule:

  • It doesn't include .jsx files (required for React components)
  • The exclude path uses an incorrect string instead of a regular expression, and has a typo (node_module instead of node_modules)

Update the module rules section to:

module: {
  rules: [
    { 
      test: /\.(js|jsx)$/, 
      exclude: /node_modules/, 
      use: 'babel-loader' 
    },
    { test: /\.css$/, use: ['style-loader', 'css-loader'] },
    { test: /\.(png|jpe?g|svg|gif)$/, use: 'file-loader' }
  ]
},

(Note: I also fixed the image test regex to correctly match JPEG files as jpe?g)

3. Verify Babel Configuration

Your .babelrc is already correctly set up for Babel 7, and now that we've installed the matching packages, it will work as intended. Double-check it matches this:

{ 
  "presets": [ 
    [ "@babel/preset-env", { 
      "modules": false, 
      "targets": { 
        "browsers": [ 
          "last 2 Chrome versions", 
          "last 2 Firefox versions", 
          "last 2 Safari versions", 
          "last 2 iOS versions", 
          "last 1 Android version", 
          "last 1 ChromeAndroid version", 
          "ie 11" 
        ] 
      } 
    } ], 
    "@babel/preset-react" 
  ], 
  "plugins": [ "@babel/plugin-proposal-class-properties" ] 
}

4. Test the Fix

Run your dev server again:

npm run dev

This should resolve the module parse error because:

  • Webpack now processes both .js and .jsx files
  • Babel 7 properly transpiles JSX syntax to plain JavaScript that Webpack can understand
  • All dependencies are now aligned with your configuration

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:57:54