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

React Leaflet构建失败:已尝试常见方案仍无法解决

解决React-Leaflet模块解析错误(Unexpected token)的方案

我已尝试修改browserslist、删除缓存等方案,但问题仍未解决,报错详情如下:

./node_modules/@react-leaflet/core/lib/path.js 10:39
Module parse failed: Unexpected token (10:39)
You may need an appropriate loader to handle this file type.
|   useEffect(function updatePathOptions() {
|     if (props.pathOptions !== optionsRef.current) {
>       var options = props.pathOptions ?? {};
|       element.instance.setStyle(options);
|       optionsRef.current = options;

我的package.json依赖部分:

{
  "name": "bouse",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^9.10.0",
    "leaflet": "^1.9.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.4.0",
    "react-leaflet": "^4.1.0",
    "react-router-dom": "^6.4.1",
    "react-scripts": "^2.1.3",
    "react-toastify": "^9.0.0",
    "swiper": "^6.8.1",
    "uuid": "^9.0.0",
    "web-vitals": "^2.1.4"
  }
}

问题根源

报错里的??是空值合并运算符,属于ES2020语法,但你使用的react-scripts@2.1.3版本过旧,其内置的Babel配置默认不支持该语法;同时react-leaflet@4.1.0依赖的@react-leaflet/core使用了该新语法,且旧版react-scripts不会转译node_modules内的包,导致解析失败。

解决方案

方案1:升级react-scripts(推荐)

旧版react-scripts与React18兼容性较差,直接升级到最新稳定版可解决语法支持问题:

  1. 卸载旧版本:
npm uninstall react-scripts
  1. 安装最新版本:
npm install react-scripts@latest
  1. 清理缓存并重启项目:
npm cache clean --force
npm start

方案2:不升级react-scripts,手动配置Babel支持

如果无法升级react-scripts,需通过react-app-rewired修改配置,让Babel转译@react-leaflet/core并支持空值合并运算符:

  1. 安装依赖包:
npm install react-app-rewired customize-cra @babel/plugin-proposal-nullish-coalescing-operator --save-dev
  1. 修改package.json中的scripts字段,替换react-scripts为react-app-rewired:
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test"
}
  1. 在项目根目录创建config-overrides.js文件,添加以下配置:
const { override, addBabelPlugin, transpileModules } = require('customize-cra');

module.exports = override(
  addBabelPlugin('@babel/plugin-proposal-nullish-coalescing-operator'),
  transpileModules(['@react-leaflet/core', 'react-leaflet'])
);
  1. 重启项目即可。

内容的提问来源于stack exchange,提问作者Papa Kow Dadson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:35:22