英文:
Error when trying to build nextjs using React-Leaflet (T3 stack)
问题
我有一些困难尝试将react-leaflet与nextjs集成。在我使用地图时,我在我的index.tsx文件中使用动态导入。当我使用"pnpm dev / run"运行应用程序时,这运行正常,但当我尝试构建应用程序时出现问题。使用"pnpm build"编译正常,但在"收集页面数据"步骤时出现崩溃并返回错误,完整的日志如下:
日志
$ pnpm build
> tjenesteplattform@0.1.0 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\leaflet@1.9.3\node_modules\leaflet\dist\leaflet-src.js:230:19
at C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules\.pnpm\leaflet@1.9.3\node_modules\leaflet\dist\leaflet-src.js:7:66
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)
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\next@13.1.1_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='© <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='© 2023 Norkart AS/Geovekst og kommunene/OpenStreetMap/NASA, Meti'
/>
)}
<LocationMarker />
</MapContainer>
</div>
);
}
return null;
};
export default Map;
Index.tsx
import dynamic from
<details>
<summary>英文:</summary>
I have some trouble trying to integrate **react-leaflet** with nextjs. I use dynamic import when I use the map in my **index.tsx** file. This works fine when I run the application using "pnpm dev / run", the problem arises when i try to build the application. When using "pnpm build" it compiles just fine but when it's on the step "collecting page data" it crashes and returns and error, the compleete log is below:
**Log**
$ pnpm build
> tjenesteplattform@0.1.0 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\leaflet@1.9.3\node_modules\leaflet\dist\leaflet-src.js:230:19
at C:\Users\OlavA\OneDrive\Desktop\Tjenesteplattform\node_modules.pnpm\leaflet@1.9.3\node_modules\leaflet\dist\leaflet-src.js:7:66
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)
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\next@13.1.1_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**
```ts
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;
答案1
得分: 4
我遇到了相同的问题,对于相同的堆栈,我的地图组件与页面组件并排。 next dev
正常工作,但 next build
失败。NextJS 在最后的构建步骤中收集了一些 页面数据,而对我来说解决方法是将禁用SSR的地图组件从页面文件夹中移出,例如移到专门的 组件文件夹 中。这有助于构建。
英文:
I had the same problem for the same stack, and my map components were side-by-side with the page component. next dev
worked fine, but next build
failed.
NextJS collects some page data during the last build step and the solution for me was to move out my map components with disabled SSR out from the pages folder, for example to the dedicated components folder.
That helped with the build.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论