Description
In Node v14.5.0, I used to be able to do the following, from a package with type: "module"
:
import {compare} from "fast-json-patch";
However, after updating to Node v14.17.1, the named-import above fails:
import { compare } from "fast-json-patch";
^^^^^^^
SyntaxError: Named export 'compare' not found. The requested module 'fast-json-patch' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'fast-json-patch';
const { compare } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
The problem seems to be that Node:
- Looks at the
main
field rather than themodule
field. (unintuitive since the package doing the importing is oftype: module
, but I guess this is part of theirmain
->exports
deprecation plan, as explained below) - Sees that it's a CommonJS module. (so without explicit named exports)
- Nonetheless, attempts to parse it with the new named-imports from common-js system -- but fails, because the index.js file does not use patterns that cjs-module-lexer recognizes.
- Since there was no ESModule named-export matching "compare", and the commonjs static-analysis also failed to find a match, Node throws an error because it can't resolve the named-import.
I've looked around some, and I believe this has something to do with the changes discussed here: nodejs/node#36918
Basically, they are trying to encourage people to shift from using the main
field to using the exports
field (usage instructions here). In the process, it appears they changed the way Node handles packages with both main
and module
fields (as is true for this fast-json-patch library's package.json file), with the outcome being that Node apparently now favors the main
field over module
even if the package that's doing the importing is of type: "module"
(though prefers the exports
field over both of those, of course).
All that to say, the solution is straight-forward: just update the package.json file to supply the new exports
field:
[...]
"main": "index.js", // not needed anymore (for NodeJS anyway), but probably good to keep for back-compatibility
"exports": {
"import": "./index.mjs",
"require": "./index.js"
},
"module": "index.mjs",
[...]
I've tried applying the changes above to my local ./node_modules/fast-json-patch/package.json
, and it fixes the error as expected.