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

Babel Loader解析失败:类属性箭头函数无法识别的问题求助

Fixing "Unexpected token" Error for Class Field Arrow Functions in Webpack + Babel

Let's break down why you're hitting this error and how to fix it step by step:

Why the Error Happens

The syntax you're using (example = (params) => { return params }) is called class field syntax—it lets you define instance properties directly in a class, including arrow functions that bind this to the class instance. This wasn't part of early ES standards (like ES2015) and requires an extra Babel plugin to transpile, even with stage-2. Also, your error points to a file in node_modules, which your Webpack config is currently excluding from Babel processing—so that untranspiled syntax is breaking the build.

Step 1: Update Babel Dependencies

Old Babel presets like babel-preset-env, babel-preset-es2015, and stage-2 are deprecated. Switch to the modern @babel package ecosystem:

# Uninstall old packages
npm uninstall babel-preset-env babel-preset-react babel-preset-es2015 babel-preset-stage-2 babel-loader

# Install modern replacements
npm install @babel/core @babel/preset-env @babel/preset-react @babel/plugin-proposal-class-properties babel-loader --save-dev

Step 2: Update Your .babelrc Configuration

Replace your old presets with the modern ones, and add the plugin for class fields:

{
  "presets": [
    "@babel/preset-env", // Replaces env/es2015, auto-transpiles for target environments
    "@babel/preset-react" // Handles React JSX syntax
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties" // Enables class field syntax (your arrow function property)
  ]
}

Step 3: Adjust Webpack to Transpile the Problematic Node Module

Your error comes from ./node_modules/example/example.js, which Webpack is skipping because of exclude: /node_modules/. To fix this, modify your Webpack rule to include that specific module (so Babel processes it):

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        // Exclude node_modules except the "example" package
        exclude: /node_modules(?!\/example)/,
        use: { loader: "babel-loader" }
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  },
  plugins: [htmlPlugin]
};

Step 4: Test the Build

Run your Webpack build again—this should resolve the "Unexpected token" error, as Babel will now transpile both your code and the problematic third-party module's class field syntax.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:41