reactjsastrojskonvakonvajs-reactjs

Cannot find module 'canvas' using Konva in Astro


Following the getting started example, I created a new component components/Main.tsx and added:

import { Stage, Layer, Rect, Circle, Text } from 'react-konva';

export default function Main() {
    return <Stage width={window.innerWidth} height={window.innerHeight}>
        <Layer>
            <Text text="Try to drag shapes" fontSize={15} />
            <Rect
                x={20}
                y={50}
                width={100}
                height={100}
                fill="red"
                shadowBlur={10}
                draggable
            />
            <Circle
                x={200}
                y={100}
                radius={50}
                fill="green"
                draggable
            />
        </Layer>
    </Stage>
}

Then, I added it to my index.astro by importing it in the front matter, and adding:

<Main/>

When I tried running the dev server, I got:

18:47:08 [ERROR] Cannot find module 'canvas'

I'm creating this post so I can document how I fixed it.


Solution

  • canvas is a module that only works on the client, not on the server. I assume that it was trying to prerender the stage.

    That functionality is unintended, so we skip it with the client:only directive:

    <Main client:only="react" />