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

React Leaflet编译报错:Module parse failed(Unexpected token) 求解决方案

解决React Leaflet编译失败(模块解析失败:意外的标记??)

报错里的var options = props.pathOptions ?? {};使用了ES2020的空值合并运算符,但项目编译工具(如Webpack+Babel)未配置支持该语法,导致解析失败。以下是针对性解决方案:

解决方案

情况1:Create React App项目

  • 直接升级react-scripts到4.0.0及以上版本,新版本默认支持ES2020语法:
    npm install react-scripts@latest
    # 或使用yarn
    yarn add react-scripts@latest
    
  • 若不想升级,可通过react-app-rewired修改Babel配置:
    1. 安装依赖:
      npm install react-app-rewired @babel/plugin-proposal-nullish-coalescing-operator --save-dev
      
    2. 在项目根目录创建config-overrides.js,添加内容:
      module.exports = function override(config, env) {
        config.module.rules[0].oneOf.forEach(rule => {
          if (rule.loader?.includes('babel-loader')) {
            rule.options.plugins.push('@babel/plugin-proposal-nullish-coalescing-operator');
          }
        });
        return config;
      };
      
    3. 修改package.json的启动命令:
      "scripts": {
        "start": "react-app-rewired start",
        "build": "react-app-rewired build",
        "test": "react-app-rewired test"
      }
      

情况2:自定义Webpack+Babel项目

  • 安装并启用Babel插件支持空值合并运算符:
    1. 安装插件:
      npm install @babel/plugin-proposal-nullish-coalescing-operator --save-dev
      
    2. 修改Babel配置文件(.babelrc或babel.config.js):
      {
        "presets": ["@babel/preset-env", "@babel/preset-react"],
        "plugins": ["@babel/plugin-proposal-nullish-coalescing-operator"]
      }
      
  • 或升级@babel/preset-env并配置目标环境,让它自动适配所需语法:
    {
      "presets": [
        ["@babel/preset-env", {
          "targets": "> 0.25%, not dead",
          "useBuiltIns": "usage",
          "corejs": 3
        }],
        "@babel/preset-react"
      ]
    }
    

情况3:降级React Leaflet版本

若不想调整编译配置,可降级到不使用ES2020语法的版本(注意匹配Leaflet版本):

npm install react-leaflet@2.8.0 leaflet@1.7.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:24:23