I’m trying to import a JSON file in ECMAScript 6, but the following doesn’t work:
import config from '../config.json'
This works fine for JavaScript files, but not for JSON. I read that in Node.js (especially since version 14), JSON imports in ES modules aren’t fully supported yet, and import assertions are still experimental.
Are there any other ways to javascript import json
or work around this limitation?
You can use import with assert { type: 'json' }
:
import config from './config.json' assert { type: 'json' };
console.log(config);
It works in modern environments (Node.js ≥20 with "type": "module"
in package.json
). Also, it is supported in Vite, Webpack 5, or native browser modules (behind flags).
When use, make sure you are using the .mjs
extension or setting "type": "module"
in your package.json
.
Can you please use fs.readFileSync()
and JSON.parse()
:
const fs = require('fs');
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
console.log(config);
Why use this?
- Fully supported in all versions of Node.js (CommonJS style).
- Doesn’t require import assertions or module flags.
You can use dynamic import()
to load modules or resources like JSON files asynchronously at runtime. For example:
const config = await import('./config.json', {
assert: { type: 'json' }
});
console.log(config.default);
Why use this:
Works in modern environments (Node ≥17.5 with flags, browsers with module support)
Useful for conditional or dynamic imports