"Cannot use import statement outside a module" when loading from ESModules package
See original GitHub issueBug report
Description / Observed Behavior
When I import SWR from a package using ESModules (type
is set to "module"
in the package.json), it fails to load SWR with the error in the title. For me this is specifically happening with a wrapper library for swr that I’m using, which uses ESM.
I think that this is because the esm build of swr is using the extension .esm.js
not .mjs
, so Node doesn’t realise it is using ESM (even though it is under import
in the exports object in swr’s package.json, which might be a bug with node). In fact, renaming the entrypoint from index.esm.js
to index.mjs
fixes the issue.
The 0.5 build (which works) doesn’t use exports
so Node will be importing the CJS build, which is probably why that version works.
Expected Behavior
The library should import fine, without Node complaining that it is using import
statements.
Repro Steps / Code Example
All you need to do is import useSWR from swr in a package that requires swr>=1.0.0 and has its type set to module:
// index.js
import useSWR from "swr";
// package.json
{
"type": "module",
"dependencies": {
"swr": "^1.1.2"
}
}
Additional Context
SWR version: 1.1.2 (seems to effect every version >=1.0.0) Node verison: 14.17.6 (although it doesn’t work on 16.13.1 too)
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Sounds like a good idea. I can try to see if there’s any workarounds for it 🙏
https://twitter.com/antfu7/status/1476438919000772609 there’re some discussions in this thread that might be helpful.