我在尝试解决React-Leaflet
/ Leaflet
希望定义窗口并导致Gatsby构建npm run build
失败时遇到麻烦。
错误消息:
WebpackError: window is not defined
- leaflet-src.js:230
~/leaflet/dist/leaflet-src.js:230:1
- leaflet-src.js:7 version
~/leaflet/dist/leaflet-src.js:7:1
- leaflet-src.js:10 Object.exports.__esModule
~/leaflet/dist/leaflet-src.js:10:2
- AttributionControl.js:5 Object.<anonymous>
~/react-leaflet/lib/AttributionControl.js:5:1
- index.js:26 Object.exports.__esModule
~/react-leaflet/lib/index.js:26:1
- map.js:2 Object.exports.__esModule
src/pages/map.js:2:1
Gatsby文档列出了一些可能的方案或解决方案。 https://www.gatsbyjs.org/docs/debugging-html-builds/#fixing-third-party-modules
因此,通过尝试遵循列出的示例,我尝试添加gatsby-node.js
gatsby-node.js
exports.modifyWebpackConfig = ({ config, stage }) => {
if (stage === 'build-html') {
config.loader('null', {
test: /react-leaflet/,
loader: 'null-loader',
})
}
}
test: /leaflet/
和test: /react-leaflet/
But that spits out a WebpackError: Minified React error #130
我非常感谢您为摆脱这些构建错误提供的帮助。
非常感谢。
步骤和代码
$ gatsby new leaflet
$ cd leaflet && npm install
$ npm install react-leaflet leaflet react react-dom
src/pages/map.js
map.js
import React, { Component } from 'react'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet'
export default class SimpleExample extends Component {
state = {
lat: 51.505,
lng: -0.09,
zoom: 13,
}
render() {
const position = [this.state.lat, this.state.lng]
return (
<Map center={position} zoom={this.state.zoom}>
<TileLayer
attribution="&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</Map>
)
}
}
答案 0 :(得分:3)
我将使用您拥有的ModifyWebpackConfig代码。缩小错误是因为现在</script>
是一个空模块,当它尝试使用react-leaflet组件构建任何页面时,将导致错误。您必须将地图包装起来以查看窗口是否可用。这样,它将在服务器端渲染中被跳过。
在React中,它看起来像这样。
react-leaflet
答案 1 :(得分:0)
根据2019年10月的盖茨比版本,迎接未来的读者; API与OP版本相比有所变化。
gatsby-node.js
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === 'build-html') {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-leaflet|leaflet/,
use: loaders.null(),
},
],
},
})
}
}