I use @nivo/pie with "gatsby": "^3.13.0"
.
But I got an error when I gatsby build.
WebpackError: ReferenceError: ResizeObserver is not defined
Nivo's version is "@nivo/pie": "^0.79.1".
I have no idea to solve it. I would be appreciate if you could give me some advice.
And here is the React code using nivo's pie chart.
PieChart.tsx
import React from 'react'
import { ResponsivePie } from '@nivo/pie'
const PieChart: React.FC = ({ data }) => {
return (
<>
<div>
<ResponsivePie
data={data}
margin={{ top: 30, right: 80, bottom: 70, left: 80 }}
borderColor={{
from: 'color',
modifiers: [
[
'darker',
0.2,
],
],
}}
arcLabelsTextColor={{
from: 'color',
modifiers: [
[
'darker',
2,
],
],
}}
fill={[
{
match: {
id: 'ruby',
},
id: 'dots',
},
]}
legends={[
{
anchor: 'bottom-right',
direction: 'column',
justify: false,
translateX: 0,
translateY: -1,
},
]}
/>
</div>
</>
)
}
export default PieChart
===================================================================
I could fix it after I updated gatsby-node.js. But I got another error WebpackError: Minified React error #130;
. And I could fix it by this final code. There's no build error.
PieChart.tsx
import React from 'react'
import { ResponsivePie } from '@nivo/pie'
const PieChart: React.FC = ({ data }) => {
return (
<>
{typeof window !== 'undefined' && ResponsivePie &&
<ResponsivePie
data={data}
...
/>}
</>
)
}
export default PieChart
Thank you.
Try using a null loader on Gatsby's SSR. In your gatsby-node.js
:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /@nivo\/pie/,
use: loaders.null(),
},
],
},
})
}
}
Normally this kind of issue (gatsby develop
OK vs gatsby build
KO) are related to webpack's bundling on the server (Server-Side Rendering), especially when dealing with third-party dependencies that interact with the window
or other global objects (such as document
) like chart modules do. This happens because when you run gatsby build
your code is interpreted by the Node server, where there's no window available yet. On the other hand, gatsby develop
is interpreted by the browser, where there is.
With this approach, you are adding a dummy loader (null
) to webpacks to load the dependency on the client-side, where the window
is available.
Keep in mind that test: /@nivo\/pie/
is a regular expression (that's why is between slashes, /
) that tests the node_modules
folder so ensure that /@nivo\/pie/
is a valid path.