如何在ecmascript 6中导入json文件?

时间:2016-01-22 10:13:23

标签: json import ecmascript-6

如何在Ecmascript 6中访问json文件? 以下不起作用:

import config from '../config.json'

如果我尝试导入JavaScript文件,这样可以正常工作。

17 个答案:

答案 0 :(得分:71)

一个简单的解决方法:

<强> config.js

export default
{
  // my json here...
}

...然后

import config from '../config.js'

不允许导入现有的.json文件,但可以完成任务。

答案 1 :(得分:44)

不幸的是,ES6 / ES2015不支持通过模块导入语法加载JSON。 ...

有很多方法可以做到。根据您的需求,您可以查看如何在JavaScript中读取文件(如果您在浏览器中运行,则可以选择$http)或使用other questions中所述的其他加载器(假设您使用的是NodeJS)。

IMO最简单的方法可能就是将JSON作为JS对象放入ES6模块并导出它。这样你就可以在需要的地方导入它。

另外值得注意的是,如果您正在使用Webpack,导入JSON文件will work by default(自window.FileReader起)。

webpack >= v2.0.0

答案 2 :(得分:39)

在ES6 / ES2015中,您可以在代码中导入 json 文件。

// ES6/ES2015

import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

参考文献:

  1. https://hackernoon.com/import-json-into-typescript-8d465beded79

  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

答案 3 :(得分:19)

我正在使用babel + browserify,我在目录./i18n/locale-en.json中有一个JSON文件,带有翻译名称空间(与ngTranslate一起使用)。

无需从JSON文件中导出任何内容(btw不可能),我可以使用以下语法对其内容进行默认导入:

import translationsJSON from './i18n/locale-en';

答案 4 :(得分:12)

在具有抓取功能的浏览器中(基本上现在都是这样):

目前,我们无法import个具有JSON mime类型的文件,只能包含具有JavaScript mime类型的文件。它可能是将来添加的功能(official discussion)。

fetch('./file.json')
  .then(response => response.json())
  .then(obj => console.log(obj))

在Node.js v13.2 +中:

当前需要使用--experimental-json-modules flag,否则默认情况下不支持。

尝试运行

node --input-type module --experimental-json-modules --eval "import obj from './file.json'; console.log(obj)"

并查看输出到控制台的obj内容。

答案 5 :(得分:4)

如果您正在使用节点,则可以:

server_name  example.org
             www.example.org
             ""
             192.168.1.1
             ;

OR

const fs = require('fs');

const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time

其他:

const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');

OR

// config.js
{
// json object here
}

// script.js

import { config } from '../config.js';

答案 6 :(得分:2)

只需执行以下操作:

import * as importedConfig from '../config.json';

然后按如下所示使用它:

const config = importedConfig.default;

答案 7 :(得分:1)

我使用它安装插件“babel-plugin-inline-json-import”,然后在 .balberc 中添加插件。

  1. 安装插件

    npm install --save-dev babel-plugin-inline-json-import

  2. babelrc 中的配置插件

    “插件”:[ “内联json导入” ]

这是我使用它的代码

import es from './es.json'
import en from './en.json'

export const dictionary = { es, en }

答案 8 :(得分:1)

导入 JSON 文件仍处于试验阶段。可以通过以下标志支持。

<块引用>

--experimental-json-modules

否则,您可以直接使用 import.meta.url 加载相对于 fs 的 JSON 文件:-

import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));

您也可以使用 module.createRequire()

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');

答案 9 :(得分:1)

我正在使用

  • vuejs,版本:2.6.12
  • vuex,版本:3.6.0
  • vuex-i18n,版本:1.13.1。

我的解决方案是:

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:"Ładowanie..."
}

messages_en.json:

{
    "loadingSpinner.default.text":"Loading..."
}

majn.js

import {messages} from './i18n/messages'
Vue.use(messages);

答案 10 :(得分:1)

从“./resource.json”导入数据 在 Chrome 91 中是可能的。 现在支持 JSON 模块。这允许开发人员静态导入 JSON,而不是依赖于动态检索它的 fetch() 函数。

https://www.stefanjudis.com/snippets/how-to-import-json-files-in-es-modules/

答案 11 :(得分:1)

感谢所有提出和实施 JSON modulesImport Assertions 的人。从 Chrome 91 开始,可以直接导入 JSON,例如:

// test.json
{
    "hello": "world"
}

// Static Import
import json from "./test.json" assert { type: "json" };
console.log(json.hello);

// Dynamic Import
const { default: json } = await import("./test.json", { assert: { type: "json" } });
console.log(json.hello);

// Dynamic Import
import("./test.json", { assert: { type: "json" } })
  .then(module => console.log(module.default.hello));

注意:其他浏览器目前可能尚未实现此功能。

答案 12 :(得分:0)

根据您的构建工具和JSON文件中的数据结构,可能需要导入default

import { default as config } from '../config.json';

例如Next.js

中的用法

答案 13 :(得分:0)

对于NodeJS v12及更高版本,--experimental-json-modules可以解决问题,而无需babel的帮助。

https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules

但是它是以commonjs形式导入的,因此尚不支持import { a, b } from 'c.json'

但是您可以这样做:

import c from 'c.json';
const { a, b } = c;

答案 14 :(得分:0)

在其他答案中,在Node.js中,甚至可以在ES模块内部使用require来读取JSON文件。我发现这在读取其他包中的文件时特别有用,因为它利用Node自己的module resolution strategy来定位文件。

必须首先使用createRequire创建ES模块中的

require

这是一个完整的示例:

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.`);

在安装了TypeScript的项目中,上面的代码将从package.json中读取并打印TypeScript版本号。

答案 15 :(得分:0)

你可以简单地。参考目录下的data.json文件

答案 16 :(得分:-1)

有点晚了,但我在尝试为我的网络应用提供基于package.json版本发送应用版本的分析时遇到了同样的问题。

配置如下:React + Redux,Webpack 3.5.6

自从Webpack 2+以来,json-loader的功能并不多,所以在摆弄它之后,我最终删除了它。

实际上对我有用的解决方案就是使用fetch。 虽然这很可能会强制执行一些代码更改以适应异步方法,但它工作得很好,特别是考虑到fetch将动态提供json解码这一事实。

所以这是:

  fetch('../../package.json')
  .then(resp => resp.json())
  .then((packageJson) => {
    console.log(packageJson.version);
  });

请记住,因为我们在这里特别谈论package.json,所以该文件通常不会捆绑在您的生产版本中(甚至是dev),因此您必须使用CopyWebpackPlugin来使用fetch时可以访问它。