next.js - 尝试使用 React-Leaflet(T3 堆栈)构建 nextjs 时出错

标签 next.js react-leaflet

我在尝试将 react-leaflet 与 nextjs 集成时遇到了一些麻烦。当我在 index.tsx 文件中使用 map 时,我使用动态导入。当我使用“pnpm dev/run”运行应用程序时,这工作正常,当我尝试构建应用程序时,问题就出现了。当使用“pnpm build”时,它编译得很好,但是当它处于“收集页面数据”步骤时,它崩溃并返回和错误,完整的日志如下:

日志

$ pnpm build

> <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9aeef0fff4ffe9eeffeaf6fbeeeefcf5e8f7daaab4abb4aa" rel="noreferrer noopener nofollow">[email protected]</a> build C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform
> next build

info  - Loaded env from C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\.env
warn  - Invalid next.config.js options detected: 
  - The root value has an unexpected property, styledComponents, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, modularizeImports, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, skipMiddlewareUrlNormalize, skipTrailingSlashRedirect, staticPageGenerationTimeout, swcMinify, trailingSlash, transpilePackages, typescript, useFileSystemPublicRoutes, webpack).

See more info here: https://nextjs.org/docs/messages/invalid-next-config
info  - Linting and checking validity of types .warn  - The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config
info  - Linting and checking validity of types
info  - Creating an optimized production build
info  - Compiled successfully
info  - Collecting page data ...ReferenceError: window is not defined
    at C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e424b4f48424b5a6e1f0017001d" rel="noreferrer noopener nofollow">[email protected]</a>\node_modules\leaflet\dist\leaflet-src.js:230:19
    at C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e626b6f68626b7a4e3f2037203d" rel="noreferrer noopener nofollow">[email protected]</a>\node_modules\leaflet\dist\leaflet-src.js:7:66
    at Object.<anonymous> (C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c60696d6a6069784c3d2235223f" rel="noreferrer noopener nofollow">[email protected]</a>\node_modules\leaflet\dist\leaflet-src.js:10:3)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at 5194 (C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\.next\server\pages\Estate\ReactMap.js:223:18)

> Build error occurred
Error: Failed to collect page data for /Estate/ReactMap
    at C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1afa4b9b581f0f2eff0eff0" rel="noreferrer noopener nofollow">[email protected]</a>_biqbaboplfbrettd7655fr4n2y\node_modules\next\dist\build\utils.js:960:15 {
  type: 'Error'
}
info  - Collecting page data . ELIFECYCLE  Command failed with exit code 1.

ReactMap.tsx

import 'leaflet/dist/leaflet.css';
import {
    MapContainer,
    TileLayer,
    useMapEvents,
    Marker,
    Polyline,
    WMSTileLayer
} from 'react-leaflet';
import { useState } from 'react';
import L, { LatLng } from 'leaflet';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css';
import 'leaflet-defaulticon-compatibility';
import { getEstateInfo } from '../../server/api/norkart';
import { EstateInfo } from '../../types';

const isServer = (): boolean => typeof window === 'undefined';

const markerIcon = new L.Icon({
    iconUrl: './marker.png',
    iconRetinaUrl: './marker.png',
    iconAnchor: [32, 64],
    iconSize: [64, 64]
});

const LocationMarker = () => {
    const [position, setPosition] = useState<LatLng>();
    const [estateInfo, setEstateInfo] = useState<EstateInfo>();

    useMapEvents({
        click(e) {
            setPosition(e.latlng);
            getEstateInfo([e.latlng.lat, e.latlng.lng]).then((data) => {
                setEstateInfo(data);
            });
        }
    });

    return position === undefined ? null : (
        <div>
            <Marker position={position} icon={markerIcon} />
            {estateInfo && estateInfo.Geometri && (
                <Polyline
                    pathOptions={{
                        color: 'purple',
                        opacity: 1,
                        fillColor: 'black',
                        fillOpacity: 0.5
                    }}
                    positions={estateInfo.Geometri}
                />
            )}
        </div>
    );
};

const Map = () => {
    if (!isServer()) {
        return (
            <div>
                <MapContainer
                    center={[58, 8]}
                    zoom={12}
                    style={{
                        height: '100vh',
                        borderRadius: '5',
                        position: 'relative'
                    }}
                >
                    <TileLayer
                        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
                    />
                    {false && (
                        <WMSTileLayer
                            layers='webatlas-orto-newup'
                            url='https://www.webatlas.no/maptiles/wms'
                            maxZoom={21}
                            minZoom={19}
                            attribution='&copy; 2023 Norkart AS/Geovekst og kommunene/OpenStreetMap/NASA, Meti'
                        />
                    )}
                    <LocationMarker />
                </MapContainer>
            </div>
        );
    }

    return null;
};

export default Map;

Index.tsx

import dynamic from 'next/dynamic';
import { type NextPage } from 'next';
import Head from 'next/head';
import React from 'react';
import { Container } from '@chakra-ui/react';
import styles from './index.module.css';
import LandingPage from './LandingPage';

import { colors } from '../styles/Theme';

const Home: NextPage = () => {
    const MapNoSSR = dynamic(() => import('./Estate/ReactMap'), { ssr: false });
    return (
        <>
            <Head>
                <title>Create T3 App</title>
                <meta name='description' content='Generated by create-t3-app' />
                <link rel='icon' href='/favicon.ico' />
            </Head>
            <main className={styles.main}>
                <Container
                    backgroundColor={colors.white}
                    maxW='80%'
                    p={20}
                    borderRadius={3}
                >
                    <LandingPage />
                    <MapNoSSR />
                </Container>
            </main>
        </>
    );
};

export default Home;

最佳答案

对于相同的堆栈,我遇到了同样的问题,并且我的 map 组件与页面组件并排。 下一个开发工作正常,但下一个构建失败了。
NextJS 在最后一个构建步骤中收集一些页面数据,对我来说,解决方案是将禁用 SSR 的 map 组件从页面文件夹中移出,例如移至专用的组件文件夹。
这有助于构建。

关于next.js - 尝试使用 React-Leaflet(T3 堆栈)构建 nextjs 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75743375/

相关文章:

react-leaflet - 我如何为玩笑测试模拟传单?

javascript - 如何在 react 传单中动态移动和旋转标记?

popup - react 传单弹出窗口不起作用,鼠标悬停时光标不会改变

javascript - Next Js 结合外部 REST API 身份验证和授权

next.js - 如何仅在特定页面上将 &lt;script&gt; 小部件嵌入 next.js 中?

reactjs - Next.js |有没有办法呈现 .xml 文件?

javascript - React-leaflet:添加 TopoJSON 层

typescript - 使用 TypeScript 使用 HOC 封装的页面的每页布局

reactjs - NextJS 中未加载 SCSS 模块

javascript - Leaflet JS (react-leaflet) - 填充透明颜色的边界框