standard-things / esm

Tomorrow's ECMAScript modules today!
Other
5.26k stars 146 forks source link

*.mjs suffix does not load "module" entry #795

Closed michaelfig closed 5 years ago

michaelfig commented 5 years ago

First off, thanks so much for esm!

I'm running into a problem when using it with *.mjs files. Here is a minimal test case:

$ mkdir t
$ npm i esm @michaelfig/slog
$ cat > t.js <<EOF
import { slog } from '@michaelfig/slog';
EOF
$ node -r esm ./t.js
$ cp t.js t.mjs
$ node -r esm ./t.mjs
/Users/michael/t/t.mjs:1
SyntaxError: The requested module 'file:///Users/michael/t/node_modules/@michaelfig/slog/dist/slog.cjs.js' does not provide an export named 'slog'
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
$

I would have expected that @michaelfig/slog could be imported successfully both in t.js and t.mjs. A clue is found in the @michaelfig/slog/package.json:

{
  "main": "dist/slog.cjs.js",
  "module": "dist/slog.esm.js",
}

So, when the file is named *.mjs, it uses the "main" entry instead of the "module" entry. Shouldn't it be consistent?

Note that I haven't specified any esm options, just the defaults.

Any help you can offer would be most appreciated, Michael.

jdalton commented 5 years ago

Shouldn't it be consistent?

Hi @michaelfig!

The esm loader doesn't apply any options to .mjs files. From the readme:

🔒 .mjs files are limited to basic functionality without support for esm options.

This is because .mjs files align with the experimental support of Node (pre-Node v12 at the moment). If you stick with .js you'll be fine though as Node will eventually ship a mechanism to use .js files too.

michaelfig commented 5 years ago

Thanks, .js works like a charm!