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

在Next.js中使用react-leaflet遇问题:window未定义及ChunkLoadError

解决Next.js中Leaflet地图的window is not defined及ChunkLoadError问题

1. 检查并修正动态导入路径

你遇到的ChunkLoadError大概率是动态导入路径错误导致的。确认import("./NewAd/map")中的相对路径和你的项目文件结构完全匹配,比如如果Map组件文件路径是components/common/Advertisement/NewAd/map.tsx,那么导入路径要根据当前文件位置调整(比如从adPage.tsx导入的话,路径可能是./NewAd/map或者../NewAd/map,视层级而定)。注意路径大小写,Linux/macOS环境下大小写不匹配也会触发加载失败。

2. 正确的无SSR动态导入写法

使用Next.js的dynamic导入时,确保关闭SSR并可选添加加载状态,避免空白或错误:

import dynamic from 'next/dynamic';

// 替换为你实际的Map组件路径
const MapWithNoSSR = dynamic(() => import('./NewAd/map'), {
  ssr: false,
  loading: () => <div style={{height: '50vh'}}>加载地图中...</div> // 保持容器高度,避免布局跳动
});

// 在组件中使用
return <MapWithNoSSR lat={yourLat} lng={yourLng} />;

3. 在Map组件中添加客户端渲染校验

为了彻底避免window is not defined错误,可以在Map组件内部添加客户端环境校验,确保只在浏览器中渲染:

import { useState, useEffect } from "react";
import { MapContainer, TileLayer, Marker, useMapEvents } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet-defaulticon-compatibility";

const Map = ({ lat, lng }) => {
  const [position, setPosition] = useState<[number, number]>([51.505, 51.505]);
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    // 仅在客户端设置为true
    setIsClient(true);
  }, []);

  // 客户端渲染前返回空或加载占位
  if (!isClient) return <div style={{height: '50vh'}}></div>;

  function Mark() {
    const map = useMapEvents({
      click: ({ latlng }) => {
        setPosition([latlng.lat, latlng.lng]);
      },
    });
    return <Marker position={position} />;
  }

  return (
    <MapContainer
      center={[lat, lng] || [35.7219, 51.3347]}
      zoom={6}
      scrollWheelZoom={false}
      style={{ height: "50vh", width: '100%' }} // 确保地图容器有明确尺寸
    >
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      <Mark />
    </MapContainer>
  );
};

export default Map;

4. 清理缓存并重启服务器

如果以上操作后仍有问题,清理Next.js缓存并重启开发服务器:

  • 停止当前运行的npm run dev/yarn dev进程
  • 删除项目根目录下的.next文件夹
  • 重新启动开发服务器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:54:24