Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created July 25, 2017 19:54
Show Gist options
  • Save Rich-Harris/fe01e28a1e7f8d6b52087bec0f23a103 to your computer and use it in GitHub Desktop.
Save Rich-Harris/fe01e28a1e7f8d6b52087bec0f23a103 to your computer and use it in GitHub Desktop.
Should `import data from './data.json'` be possible?

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.

2. I'm building something that needs to run in browsers and in Node, and I'm okay with build tools

Great! If you're using a bundler, this is a solved problem.

3. I'm building something that only needs to run in Node

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment