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

使用React19+Webpack+TS引入react-leaflet-markercluster报exports未定义错误

解决react-leaflet-markercluster在React 19+Webpack项目中的"exports is not defined"错误

这个错误源于Webpack对CommonJS模块的处理逻辑与react-leaflet-markercluster的模块输出格式不兼容,以下是具体修复方案:

  • 调整Webpack配置,优先处理ES模块并转译CommonJS代码
    在webpack.config.js中添加或修改相关配置,让Webpack优先加载包的ES模块版本,并对依赖的CommonJS代码进行转译:

    const path = require('path');
    
    module.exports = {
      // 其他已有配置
      resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        exportsFields: ['module', 'main'] // 优先读取包的module字段(ES模块)
      },
      module: {
        rules: [
          // 转译react-leaflet-markercluster及其依赖的CommonJS代码
          {
            test: /\.(js|jsx)$/,
            include: /node_modules\/(react-leaflet-markercluster|leaflet.markercluster)/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env', '@babel/preset-react']
              }
            }
          },
          // TypeScript处理规则示例
          {
            test: /\.(ts|tsx)$/,
            exclude: /node_modules/,
            use: 'ts-loader'
          }
        ]
      },
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        environment: {
          commonjs: false // 禁用CommonJS环境模拟,避免全局exports变量冲突
        }
      }
    };
    
  • 确认依赖版本兼容性
    react-leaflet-markercluster v5.x需要搭配react-leaflet v4.x及以上版本,同时确保leaflet版本适配。执行以下命令检查并升级:

    # 查看当前依赖版本
    npm list react-leaflet leaflet
    # 升级到兼容版本
    npm install react-leaflet@latest leaflet@latest
    
  • 直接导入ES模块版本
    跳过自动解析,直接导入react-leaflet-markercluster的ES模块版本,避免加载有问题的CJS代码:

    import React from 'react';
    import { MapContainer, TileLayer, Marker } from 'react-leaflet';
    // 直接导入ES模块
    import MarkerClusterGroup from 'react-leaflet-markercluster/dist/esm/index.js';
    import 'leaflet/dist/leaflet.css';
    // 对应ES模块的样式文件
    import 'react-leaflet-markercluster/dist/esm/styles.css';
    
  • 检查Webpack的mode配置
    确保Webpack的mode设置为development或production,不要使用none,默认模式下Webpack会自动处理部分模块兼容问题。

内容的提问来源于stack exchange,提问作者Type-Style

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:55:16