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

Ola*_*and 2 react-leaflet next.js

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

\n

日志

\n
$ pnpm build\n\n> tjenesteplattform@0.1.0 build C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\n> next build\n\ninfo  - Loaded env from C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\\.env\nwarn  - Invalid next.config.js options detected: \n  - 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).\n\nSee more info here: https://nextjs.org/docs/messages/invalid-next-config\ninfo  - 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\ninfo  - Linting and checking validity of types\ninfo  - Creating an optimized production build\ninfo  - Compiled successfully\ninfo  - Collecting page data ...ReferenceError: window is not defined\n    at C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\\node_modules\\.pnpm\\leaflet@1.9.3\\node_modules\\leaflet\\dist\\leaflet-src.js:230:19\n    at C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\\node_modules\\.pnpm\\leaflet@1.9.3\\node_modules\\leaflet\\dist\\leaflet-src.js:7:66\n    at Object.<anonymous> (C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\\node_modules\\.pnpm\\leaflet@1.9.3\\node_modules\\leaflet\\dist\\leaflet-src.js:10:3)\n    at Module._compile (node:internal/modules/cjs/loader:1218:14)\n    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)\n    at Module.load (node:internal/modules/cjs/loader:1081:32)\n    at Module._load (node:internal/modules/cjs/loader:922:12)\n    at Module.require (node:internal/modules/cjs/loader:1105:19)\n    at require (node:internal/modules/cjs/helpers:103:18)\n    at 5194 (C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\\.next\\server\\pages\\Estate\\ReactMap.js:223:18)\n\n> Build error occurred\nError: Failed to collect page data for /Estate/ReactMap\n    at C:\\Users\\OlavA\\OneDrive\\Desktop\\Tjenesteplattform\\node_modules\\.pnpm\\next@13.1.1_biqbaboplfbrettd7655fr4n2y\\node_modules\\next\\dist\\build\\utils.js:960:15 {\n  type: 'Error'\n}\ninfo  - Collecting page data .\xe2\x80\x89ELIFECYCLE\xe2\x80\x89 Command failed with exit code 1.\n
Run Code Online (Sandbox Code Playgroud)\n

ReactMap.tsx

\n
import 'leaflet/dist/leaflet.css';\nimport {\n    MapContainer,\n    TileLayer,\n    useMapEvents,\n    Marker,\n    Polyline,\n    WMSTileLayer\n} from 'react-leaflet';\nimport { useState } from 'react';\nimport L, { LatLng } from 'leaflet';\nimport 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css';\nimport 'leaflet-defaulticon-compatibility';\nimport { getEstateInfo } from '../../server/api/norkart';\nimport { EstateInfo } from '../../types';\n\nconst isServer = (): boolean => typeof window === 'undefined';\n\nconst markerIcon = new L.Icon({\n    iconUrl: './marker.png',\n    iconRetinaUrl: './marker.png',\n    iconAnchor: [32, 64],\n    iconSize: [64, 64]\n});\n\nconst LocationMarker = () => {\n    const [position, setPosition] = useState<LatLng>();\n    const [estateInfo, setEstateInfo] = useState<EstateInfo>();\n\n    useMapEvents({\n        click(e) {\n            setPosition(e.latlng);\n            getEstateInfo([e.latlng.lat, e.latlng.lng]).then((data) => {\n                setEstateInfo(data);\n            });\n        }\n    });\n\n    return position === undefined ? null : (\n        <div>\n            <Marker position={position} icon={markerIcon} />\n            {estateInfo && estateInfo.Geometri && (\n                <Polyline\n                    pathOptions={{\n                        color: 'purple',\n                        opacity: 1,\n                        fillColor: 'black',\n                        fillOpacity: 0.5\n                    }}\n                    positions={estateInfo.Geometri}\n                />\n            )}\n        </div>\n    );\n};\n\nconst Map = () => {\n    if (!isServer()) {\n        return (\n            <div>\n                <MapContainer\n                    center={[58, 8]}\n                    zoom={12}\n                    style={{\n                        height: '100vh',\n                        borderRadius: '5',\n                        position: 'relative'\n                    }}\n                >\n                    <TileLayer\n                        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'\n                        url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'\n                    />\n                    {false && (\n                        <WMSTileLayer\n                            layers='webatlas-orto-newup'\n                            url='https://www.webatlas.no/maptiles/wms'\n                            maxZoom={21}\n                            minZoom={19}\n                            attribution='&copy; 2023 Norkart AS/Geovekst og kommunene/OpenStreetMap/NASA, Meti'\n                        />\n                    )}\n                    <LocationMarker />\n                </MapContainer>\n            </div>\n        );\n    }\n\n    return null;\n};\n\nexport default Map;\n
Run Code Online (Sandbox Code Playgroud)\n

索引.tsx

\n
import dynamic from 'next/dynamic';\nimport { type NextPage } from 'next';\nimport Head from 'next/head';\nimport React from 'react';\nimport { Container } from '@chakra-ui/react';\nimport styles from './index.module.css';\nimport LandingPage from './LandingPage';\n\nimport { colors } from '../styles/Theme';\n\nconst Home: NextPage = () => {\n    const MapNoSSR = dynamic(() => import('./Estate/ReactMap'), { ssr: false });\n    return (\n        <>\n            <Head>\n                <title>Create T3 App</title>\n                <meta name='description' content='Generated by create-t3-app' />\n                <link rel='icon' href='/favicon.ico' />\n            </Head>\n            <main className={styles.main}>\n                <Container\n                    backgroundColor={colors.white}\n                    maxW='80%'\n                    p={20}\n                    borderRadius={3}\n                >\n                    <LandingPage />\n                    <MapNoSSR />\n                </Container>\n            </main>\n        </>\n    );\n};\n\nexport default Home;\n\n
Run Code Online (Sandbox Code Playgroud)\n

Gle*_*nov 5

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