How can I access a JSON file in ECMAScript 6?
The following doesn't work:
import config from '../config.json'
This works fine if I try to import a JavaScript file.
This question is related to
json
import
ecmascript-6
Depending on your build tooling and the data structure within the JSON file, it may require importing the default
.
import { default as config } from '../config.json';
e.g. usage within Next.js
I used it installing the plugin "babel-plugin-inline-json-import" and then in .balberc add the plugin.
Install plugin
npm install --save-dev babel-plugin-inline-json-import
Config plugin in babelrc
"plugin": [ "inline-json-import" ]
And this is the code where I use it
import es from './es.json'
import en from './en.json'
export const dictionary = { es, en }
I'm using
My solution is:
messages.js:
import Vue from 'vue'
import Vuex from 'vuex';
import vuexI18n from 'vuex-i18n';
import translationsPl from './messages_pl'
import translationsEn from './messages_en'
Vue.use(Vuex);
export const messages = new Vuex.Store();
Vue.use(vuexI18n.plugin, messages);
Vue.i18n.add('en', translationsEn);
Vue.i18n.add('pl', translationsPl);
Vue.i18n.set('pl');
messages_pl.json:
{
"loadingSpinner.text:"Ladowanie..."
}
messages_en.json:
{
"loadingSpinner.default.text":"Loading..."
}
majn.js
import {messages} from './i18n/messages'
Vue.use(messages);
For NodeJS v12 and above, --experimental-json-modules
would do the trick, without any help from babel.
https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules
But it is imported in commonjs form, so import { a, b } from 'c.json'
is not yet supported.
But you can do:
import c from 'c.json';
const { a, b } = c;
Simply do this:
import * as importedConfig from '../config.json';
Then use it like the following:
const config = importedConfig.default;
importing JSON files are still experimental. It can be supported via the below flag.
--experimental-json-modules
otherwise you can load your JSON file relative to import.meta.url
with fs
directly:-
import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));
you can also use module.createRequire()
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');
In TypeScript or using Babel, you can import json file in your code.
// Babel
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
Reference: https://hackernoon.com/import-json-into-typescript-8d465beded79
A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.
Configuration is as follows: React + Redux, Webpack 3.5.6
The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.
The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.
So here it is:
fetch('../../package.json')
.then(resp => resp.json())
.then((packageJson) => {
console.log(packageJson.version);
});
Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.
At the moment, we can't import
files with a JSON mime type, only files with a JavaScript mime type. It might be a feature added in the future (official discussion).
fetch('./file.json')
.then(response => response.json())
.then(obj => console.log(obj))
It currently requires the --experimental-json-modules
flag, otherwise it isn't supported by default.
Try running
node --input-type module --experimental-json-modules --eval "import obj from './file.json'; console.log(obj)"
and see the obj content outputted to console.
Adding to the other answers, in Node.js it is possible to use require
to read JSON files even inside ES modules. I found this to be especially useful when reading files inside other packages, because it takes advantage of Node's own module resolution strategy to locate the file.
require
in an ES module must be first created with createRequire
.
Here is a complete example:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const packageJson = require('typescript/package.json');
console.log(`You have TypeScript version ${packageJson.version} installed.`);
In a project with TypeScript installed, the code above will read and print the TypeScript version number from package.json.
If you're using node you can:
const fs = require('fs');
const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time
OR
const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');
Else:
// config.js
{
// json object here
}
// script.js
import { config } from '../config.js';
OR
import * from '../config.json'
Unfortunately ES6/ES2015 doesn't support loading JSON via the module import syntax. But...
There are many ways you can do it. Depending on your needs you can either look into how to read files in JavaScript (window.FileReader
could be an option if you're running in the browser) or use some other loaders as described in other questions (assuming you are using NodeJS).
IMO simplest way is probably to just put the JSON as a JS object into an ES6 module and export it. That way you can just import it where you need it.
Also worth noting if you're using Webpack, importing of JSON files will work by default (since webpack >= v2.0.0
).
import config from '../config.json';
I'm using babel+browserify and I have a JSON file in a directory ./i18n/locale-en.json with translations namespace (to be used with ngTranslate).
Without having to export anything from the JSON file (which btw is not possible), I could make a default import of its content with this syntax:
import translationsJSON from './i18n/locale-en';
Source: Stackoverflow.com