standard-things / esm

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

Update esm/import to allow loading ESM from .js #847

Closed dicearr closed 2 years ago

dicearr commented 5 years ago

Motivation

In Node 12 it is possible to load ESM code from .js files as long as the closest package.json file has the property "type" set to "module". Currently esm is failing with ERR_INVALID_ESM_FILE_EXTENSION. This can be easily reproduced by executing:

$ cd $(mktemp -d) \
   && npm install esm \
   && echo '{"type": "module"}' > package.json \
   && echo 'export const n = 42' > index.js \
   && echo "import {n} from './index.js'" > index.mjs \
   && node -r esm index.mjs
file:///tmp/tmp.qN6ty6WLNE/index.mjs:1
import {n} from './index.js'

Error: Cannot load module from .mjs: file:///tmp/tmp.qN6ty6WLNE/index.js
    at file:///tmp/tmp.qN6ty6WLNE/index.mjs:1
    at Generator.next (<anonymous>)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Changes

Currently esm supports loading ESM code from a .js file as long as the file that is importing the code is also .js. This made me think that ERR_INVALID_ESM_FILE_EXTENSION was only a restriction to be as close to Node 11.x modules implementation as possible.

Following that naive logic I have just removed the check. If this is a desired feature but has deeper implications I am willing to further develop it with some guidance.

mk-pmb commented 3 years ago

How do you use this? I revived the PR branch as https://github.com/mk-pmb/std-esm-node/tree/dicearr-esm-pr847 , made an empty directory /tmp/isfn3, and in there, ran

git clone --quiet --single-branch --branch=dicearr-esm-pr847 \
     https://github.com/mk-pmb/std-esm-node.git . \
  && npm install is-fn \
  && npm install . \
  && npm run build

That seems to have worked:

Hash: c6e1239d863cf8957341
Version: webpack 4.46.0
Time: 5092ms
Built at: 06/01/2021 3:43:48 AM
 Asset     Size  Chunks             Chunk Names
esm.js  774 KiB     esm  [emitted]  esm
Entrypoint esm = esm.js

WARNING in ./src/util/parse-json6.js 15:15-20
"export 'parse' was not found in 'json-6'
 @ ./src/package.js
 @ ./src/index.js

However, when I then run (in the esm repo direcory)

node -r esm -e "import isFunc from 'is-fn';"

it fails the same as #898.

dicearr commented 3 years ago

@mk-pmb, ~you only need to execute the command I provided to reproduce the issue. In any case,~ this PR didn't bring any attention so I assume I was under wrong assumptions with the problem and/or the solution.

EDIT: Sorry, I misunderstood your message. Its been a long time, so I don't think I can help you a lot. As I mentioned in the PR I took a very naive approach and I might have broken something, or the solution might be incomplete. In the end as I didn't make any progress with this PR I changed my approach so I could stop using this library.

dicearr commented 2 years ago

Closed due to inactivity.