In Node, you can do this:
const data = require('./data.json');
You can even do this (and Node will try various paths — ./data.js
, ./data/index.js
, ./data.json
, ./data/index.json
— until one matches):
const data = require('./data');
(In my opinion that's hellaciously confusing, and somewhat questionable from a performance point of view. But let's table that for now.)
So it's reasonable to ask whether the following should work, once ESM is supported:
import data from './data.json';
I believe the answer is no. Let's examine three possible scenarios:
1. I'm building something that needs to run in browsers and in Node, and I don't want to use build tools
Unless browsers are able to handle JSON imports (I don't see why they couldn't, but I'm also not aware of any plans in that direction), then the code above will fail in browsers. Therefore, allowing JSON imports would be a browser-hostile move on the part of Node.
Great! If you're using a bundler, this is a solved problem.
You can do that without using import
:
const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'data.json'), 'utf-8'));
A little verbose, sure. But if you're in favour of JSON imports because it's less to type, then the onus is on you to explain why saving those keystrokes is a higher priority than compatibility with the web.