standard-things / esm

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

Interop with CJS modules that do not export a default #822

Closed andrewplummer closed 5 years ago

andrewplummer commented 5 years ago

I've had this issue with other packages as well, but the contentful package clearly illustrates it. They are using a CJS module required from the main field in their package.json and an es-module using the module field.

When running from node, esm seems to prefer the main and loads the CJS package, however it doesn't have a default export so it complains:

SyntaxError: The requested module 'file:///Users/andrew/Experiments/contentful/node_modules/contentful/dist/es-modules/contentful.js' does not provide an export named 'default'

this can be simply reproduced using:

import contentful from 'contentful'; // script.js

and running:

node -r esm script.js

There must be something I'm missing... All I would like to do is:

  1. Use the "module" field instead to require the ES module flavor OR
  2. Get the CJS package to work... I've tried "esm": { "cjs": true }} in my package.json (as well as many different other combinations) to no avail.
dnalborczyk commented 5 years ago

hey @andrewplummer

When running from node, esm seems to prefer the main and loads the CJS package

your exception above is using the path from the module field: file:///Users/andrew/Experiments/contentful/node_modules/contentful /dist/es-modules/contentful.js

not sure how you did it, but forcing esm to use the module field you could specify the mainFields option. e.g. mainFields: ['module', 'main'] . I believe the order also matters. the docs are indeed a bit sparse.

andrewplummer commented 5 years ago

This is what my package.json looks like:

{
  "name": "contentful",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "node -r esm ./test"
  },
  "esm": {
    "cjs": true,
    "mainFields": ["module", "main"]
  },
  "license": "MIT",
  "dependencies": {
    "contentful": "^7.8.0",
    "esm": "^3.2.25"
  }
}

I've tried all different combinations of module and main (including none at all) to no avail....

dnalborczyk commented 5 years ago

looks fine. cjs: true is the default btw.

if you look into node_modules/contentful/dist/es-modules/contentful.js there is no default export.

you can also check with:

import * as ns from 'contentful'
console.log(ns)
andrewplummer commented 5 years ago

That worked for me! Thank you!