pmndrs/react-three-fiber

Can't import using javascript modules / importmaps

FredrikNoren opened this issue · 1 comments

Hi, the following doesn't seem to work:

<body>
    <div id="root"></div>
    <script type="importmap">
        {
            "imports": {
                "react": "https://esm.sh/react@18.3.1",
                "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",
                "@react-three/fiber": "https://esm.sh/@react-three/fiber@8.17.7"
            }
        }
    </script>
    <script type="module">
        import React from 'react';
        import ReactDOM from 'react-dom/client';
        import { Canvas } from "@react-three/fiber";

        function Game() {
            return React.createElement(Canvas, null);
        }

        const container = document.getElementById('root');
        const root = ReactDOM.createRoot(container);
        root.render(React.createElement(Game, null));
    </script>

</body>

I'm getting this error:
Screenshot 2024-09-11 at 13 44 32
Or here's the same error if I switch to dev versions:
Screenshot 2024-09-11 at 13 45 03

Here's a codepen with it: https://codepen.io/FredrikNoren/pen/PorLRxx

Any ideas why this might not work?

Related issues: #3268

I figured out the error: when importing using esm.sh I needed to specify which dependencies are external. Here's a working version:

<body>
    <div id="root"></div>
    <script type="importmap">
        {
            "imports": {
                "react": "https://esm.sh/react@18.3.1?dev",
                "react/": "https://esm.sh/react@18.3.1&dev/",
                "react-dom": "https://esm.sh/react-dom@18.3.1?dev",
                "react-dom/": "https://esm.sh/react-dom@18.3.1&dev/",
                "@react-three/fiber": "https://esm.sh/@react-three/fiber@8.17.7?dev&external=react,react-dom"
            }
        }
    </script>
    <script type="module" src="https://esm.sh/run"></script>
    <script type="text/babel">
        import React from 'react';
        import ReactDOM from 'react-dom/client';
        import { Canvas } from "@react-three/fiber";

        function Game() {
            // return React.createElement(Canvas, null);
            return <Canvas camera={{ position: [0, 5, 10] }} resize={{ offsetSize: true }}>
                <ambientLight intensity={0.5} />
                <pointLight position={[10, 10, 10]} />
                <mesh >
                    <boxGeometry args={[2, 2, 2]} />
                    <meshStandardMaterial color="hotpink" />
                </mesh>
            </Canvas>;
        }

        const container = document.getElementById('root');
        const root = ReactDOM.createRoot(container);
        root.render(React.createElement(Game, null));
    </script>

</body>