使用React-Leaflet构建Next.js时出现错误 (T3堆栈)。

huangapple go评论62阅读模式
英文:

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='&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

<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 &quot;pnpm dev / run&quot;, the problem arises when i try to build the application. When using &quot;pnpm build&quot; it compiles just fine but when it&#39;s on the step &quot;collecting page data&quot; 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 &#39;leaflet/dist/leaflet.css&#39;;
import {
MapContainer,
TileLayer,
useMapEvents,
Marker,
Polyline,
WMSTileLayer
} from &#39;react-leaflet&#39;;
import { useState } from &#39;react&#39;;
import L, { LatLng } from &#39;leaflet&#39;;
import &#39;leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css&#39;;
import &#39;leaflet-defaulticon-compatibility&#39;;
import { getEstateInfo } from &#39;../../server/api/norkart&#39;;
import { EstateInfo } from &#39;../../types&#39;;
const isServer = (): boolean =&gt; typeof window === &#39;undefined&#39;;
const markerIcon = new L.Icon({
iconUrl: &#39;./marker.png&#39;,
iconRetinaUrl: &#39;./marker.png&#39;,
iconAnchor: [32, 64],
iconSize: [64, 64]
});
const LocationMarker = () =&gt; {
const [position, setPosition] = useState&lt;LatLng&gt;();
const [estateInfo, setEstateInfo] = useState&lt;EstateInfo&gt;();
useMapEvents({
click(e) {
setPosition(e.latlng);
getEstateInfo([e.latlng.lat, e.latlng.lng]).then((data) =&gt; {
setEstateInfo(data);
});
}
});
return position === undefined ? null : (
&lt;div&gt;
&lt;Marker position={position} icon={markerIcon} /&gt;
{estateInfo &amp;&amp; estateInfo.Geometri &amp;&amp; (
&lt;Polyline
pathOptions={{
color: &#39;purple&#39;,
opacity: 1,
fillColor: &#39;black&#39;,
fillOpacity: 0.5
}}
positions={estateInfo.Geometri}
/&gt;
)}
&lt;/div&gt;
);
};
const Map = () =&gt; {
if (!isServer()) {
return (
&lt;div&gt;
&lt;MapContainer
center={[58, 8]}
zoom={12}
style={{
height: &#39;100vh&#39;,
borderRadius: &#39;5&#39;,
position: &#39;relative&#39;
}}
&gt;
&lt;TileLayer
attribution=&#39;&amp;copy; &lt;a href=&quot;http://osm.org/copyright&quot;&gt;OpenStreetMap&lt;/a&gt; contributors&#39;
url=&#39;https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&#39;
/&gt;
{false &amp;&amp; (
&lt;WMSTileLayer
layers=&#39;webatlas-orto-newup&#39;
url=&#39;https://www.webatlas.no/maptiles/wms&#39;
maxZoom={21}
minZoom={19}
attribution=&#39;&amp;copy; 2023 Norkart AS/Geovekst og kommunene/OpenStreetMap/NASA, Meti&#39;
/&gt;
)}
&lt;LocationMarker /&gt;
&lt;/MapContainer&gt;
&lt;/div&gt;
);
}
return null;
};
export default Map;

Index.tsx

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

import { colors } from &#39;../styles/Theme&#39;;

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

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.

huangapple
  • 本文由 发表于 2023年3月15日 18:21:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定