dexie-encrypted icon indicating copy to clipboard operation
dexie-encrypted copied to clipboard

Importing from ESM module fails

Open aguycalled opened this issue 4 years ago • 1 comments

Importing from a ESM module with Node v15.14.0 fails.

import { applyEncryptionMiddleware } from "dexie-encrypted";

Output:

node:internal/process/esm_loader:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/alex/xxx/node_modules/dexie/dist/modern/dexie.mjs
    at new NodeError (node:internal/errors:329:5)
    at Module.load (node:internal/modules/cjs/loader:970:11)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:996:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/home/alex/xxx/node_modules/dexie-encrypted/dist/applyMiddleware.js:5:41)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14) {
  code: 'ERR_REQUIRE_ESM'
}

aguycalled avatar Jan 05 '22 18:01 aguycalled

Related to https://github.com/dexie/Dexie.js/issues/1439. But the only working solution is to export an ESM version of this addon. Even though this particular error would go away if upgrading dexie to 3.2.1-beta.2, it would also cause new subtle issues because it will end up with two instances of dexie module:

  • One ESM "dexie" imported from application code
  • One CommonJS "dexie" required from this addon. All parts of this addon where dexie is required would get the commonjs instance while application code uses the ESM version.

So , the solution is either to change the module format from "commonjs" to "es2015", or probably better to update the build script to produce two versions of this addon: One ESM and one commonjs, and then point them out using the "exports" field in package.json the same way as it's done in dexie's package.json.

To do:

  1. Update package.json: "build" script should be extended from just "tsc" to "tsc && tsc --module es2015 --outDir dist-esm" (this will build both the commonjs and ESM version of this module)
  2. Add an "exports" field in package.json with both require and import versions (see how dexie's package.json does it)
  3. Build and publish a new version

The end result we are after:

  • People that use import to import dexie and dexie-encrypted will get a single ES2015 version of "dexie" module.
  • People that use require to import dexie and dexie-encrypted will get a single commonjs version of "dexie" module.

dfahlander avatar Jan 07 '22 13:01 dfahlander