Skip to content

Add both Module and CommonJS support #40

Description

@yanickrochon

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions