standard-things / esm

Tomorrow's ECMAScript modules today!
Other
5.27k stars 145 forks source link

Node v12: Readme example adapted to is-fn fails with ERR_REQUIRE_ESM #898

Open mk-pmb opened 3 years ago

mk-pmb commented 3 years ago

Hi! This is probably a dupe of #868 , but more boiled down, easier to replicate, because I'll include all code to reproduce.

If I understand the 3.2.25 readme correctly, this should work, right? On Ubuntu focal 64-bit, I make a new empty directory, then run in bash:

npm install is-fn@3.0.0 esm@3.2.25 &>/dev/null \
  && grep -Fe '"version":' -- node_modules/*/package.json \
  && echo -n 'npm: '  && npm  --version \
  && echo -n 'node: ' && node --version \
  && node -r esm -e "import isFunc from 'is-fn';"

Unfortunately, it results in

node_modules/esm/package.json:  "version": "3.2.25"
node_modules/is-fn/package.json:  "version": "3.0.0"
npm: 6.14.11
node: v12.22.0
/tmp/isfn3/node_modules/is-fn/index.js:1
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /tmp/isfn3/node_modules/is-fn/index.js
require() of ES modules is not supported.
require() of /tmp/isfn3/node_modules/is-fn/index.js from /tmp/isfn3/[eval] is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /tmp/isfn3/node_modules/is-fn/package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1015:13) {
  code: 'ERR_REQUIRE_ESM'
}

Same if I make a file main.mjs and run that instead of -e, like in "Getting started" way 2.

mk-pmb commented 3 years ago

I almost managed to make a fallback to native dynamic import where it's available. However, that's Promise-based, so I won't be able to make it compatible with the sync-ness expected from a require(). How did you solve that time travel?