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

问题描述 投票:0回答:0

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

日志

$ pnpm build

> [email protected] 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\[email protected]\node_modules\leaflet\dist\leaflet-src.js:230:19
    at C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\[email protected]\node_modules\leaflet\dist\leaflet-src.js:7:66
    at Object.<anonymous> (C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\[email protected]\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\[email protected]_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;

next.js react-leaflet
© www.soinside.com 2019 - 2024. All rights reserved.