From Node.js version 17.5.0 onward, importing a JSON file is possible using Import Assertions:
import packageFile from "../../package.json" assert { type: "json" };
const {
name,
version
} = packageFile;
assert { type: "json" }
is mandatory
- Destructuring such as
{ name, version }
is not possible in the import
declaration directly
- The contents of the JSON file are exported as a default export, so they need to be imported from
default
.
The dynamic import version looks like this:
const {
default: {
name,
version
}
} = await import("../../package.json", {
assert: {
type: "json"
}
});
Since import assertions and JSON modules have only recently promoted to stage 3, older versions of Node.js might have supported an older syntax.
According to the compatibility tables on MDN for import
declarations and dynamic import
, older versions of Node.js (16.0.0 – 16.14.0 and 17.0.0 – 17.4.0) had varying support:
These versions required the --experimental-json-modules
flag:
node --experimental-json-modules about.js
Some versions did not support import assertions on dynamic import
Some versions did not support the "json"
type, specifically
Some versions relied on an older proposal which did not specify the assert
syntax yet
import pkg from ('../../package.json')
? – Tarrel.json
file location is correct. – Jink