Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add both Module and CommonJS support #40

Open
yanickrochon opened this issue Jan 22, 2021 · 0 comments
Open

Add both Module and CommonJS support #40

yanickrochon opened this issue Jan 22, 2021 · 0 comments

Comments

@yanickrochon
Copy link

I currently have an issue with this module in my project since we have upgraded Node.js to the latest stable version.

SyntaxError: The requested module 'lru_map' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
For example:
import pkg from 'lru_map';
const { LRUMap } = pkg;

The solution seems to be easy enough.

The CommonJS way

Rename the source to lru.mjs and fully support import/export, then transpile to CommonJS code to the dist folder. Then modify the package.json with the `exports" config :

   "main": "./dist/lru.js",
   "type": "commonjs",
   "exports": {
      ".": [
         {
            "import": "./lru.mjs",
            "require": "./dist/lru.js",
            "default": "./dist/lru.js"
         },
         "./dist/lru.js"
      ]
   }

The Module way

Do not rename the source file, but fully support import/export, then transpile to CommonJS code with the extension .cjs to the dist folder (i.e. ./dist/lru.cjs). The modify the package.json with the a similar exports config :

   "main": "./lru.js",
   "type": "module",
   "exports": {
      ".": [
         {
            "import": "./lru.js",
            "require": "./dist/lru.cjs",
            "default": "./lru.js"
         },
         "./lru.js"
      ]
   }

Tests

I tested this solution with both Node.js v12 and v14. It works with babel-node as well as without.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant