jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.4k stars 360 forks source link

Difficulty using named imports from an .mjs file with webpack #82

Closed quasicomputational closed 5 years ago

quasicomputational commented 5 years ago

Currently, idb offers itself in two flavours: as a CommonJS module through the browser field of package.json, and as an ES6 module through the module field.

As noted in webpack/webpack#4674, webpack prefers browser to module. Hence webpack will use the CommonJS module.

However. when importing a CommonJS module from an .mjs file, you can only use a default import, not named imports.

This is sub-optimal: idb has a perfectly good ES6 module, but webpack's not using it, leading to users not being able to write import { openDb } from "idb" in their .mjs files without extra configuration work (which itself may be of dubious correctness).

Fortunately it seems like there's a workaround, as noted in the webpack issue: browser can be a map that selectively overrides some modules, rather than being used in all cases. In this instance, it seems like we want to specifically override the main module (i.e., lib/node.js).

So something like this could work (which I haven't tested):

  "main": "lib/node.js",
  "module": "lib/idb.mjs",
  "browser": {
    "./lib/node.js": "./dist/index.js",
  },
jakearchibald commented 5 years ago

The 4.0 branch fixes this https://github.com/jakearchibald/idb/tree/4.0.0

jakearchibald commented 5 years ago

4.0.0 doesn't use .mjs due to these issues.