2020-07-07
Snowpack - The requested module '/web_modules/recoil.js' does not provide an export named 'RecoilRoot'
react, snowpack
react, snowpack
I started learning Snowpack and have been pleased with the speed and development experience.
As I was learning Recoil, a new React state management library by Facebook (but not by React core team), I was running into following error message.
Uncaught SyntaxError: The requested module '/web_modules/recoil.js' does not provide an export named 'RecoilRoot'
I will talk about how to get around the issue and this won't be about how to use Snowpack or Recoil.
I used Create Snowpack App (CSA) with a React template, @snowpack/app-template-react to bootstrap a new React project.
npx create-snowpack-app new-dir --template @snowpack/app-template-react --use-yarn
And then installed Recoil as a dependency.
yarn add recoil
I initially wrapped the root element with RecoilRoot.
1import React from "react";2import ReactDOM from "react-dom";3import App from "./App";4
5// imported 👇 as shown in the Reoil doc6// https://recoiljs.org/docs/introduction/getting-started/#recoilroot7import { RecoilRoot } from "recoil";8
9import "./index.css";10
11ReactDOM.render(12 <React.StrictMode>13 <RecoilRoot>14 <App />15 </RecoilRoot>16 </React.StrictMode>,17 document.getElementById("root"),18);19
20// Hot Module Replacement (HMR) - Remove this snippet to remove HMR.21// Learn more: https://www.snowpack.dev/#hot-module-replacement22if (import.meta.hot) {23 import.meta.hot.accept();24}
But then the error mentioned in the "Introduction" occurred.
It looks like Snowpack has an issue with CJS (CommonJS) libraries according this issue, https://github.com/pikapkg/snowpack/issues/440.
The resolution in the GitHub issue is not to use named export, but to import the whole module.
1import React from "react";2import ReactDOM from "react-dom";3import App from "./App";4
5// Import 👇 the library as a whole6import Recoil from "recoil";7
8import "./index.css";9
10ReactDOM.render(11 <React.StrictMode>12 {/* 👇 Explicitly named element */}13 <Recoil.RecoilRoot>14 <App />15 </Recoil.RecoilRoot>16 </React.StrictMode>,17 document.getElementById("root"),18);19
20// Hot Module Replacement (HMR) - Remove this snippet to remove HMR.21// Learn more: https://www.snowpack.dev/#hot-module-replacement22if (import.meta.hot) {23 import.meta.hot.accept();24}
This means, everywhere you use Recoil, you need to import the whole module. I found it a bit annoying but haven't been able to find out a better solution.
Please leave a comment if you can share a different way :)