在 .js 模块中包含 .json 文件

Include .json file in .js module

我在以下位置有一个翻译文件:

frontend/locales/en/translations.js

看起来像:

export default {
  back: "Back",
  or: "Or",
  cancel: "Cancel",
};

我想将翻译散列移动到 .json 文件中:

frontend/locales/en/translations.json

并以某种方式将其包含在 .js 文件中。

最好的方法是什么?

EcmaScript 6 modules 不允许导入 .json(或其他东西),它们只关注 javascript。

这是一个参考:

您可以使用 webpack that has a specific json-loader.

等捆绑器来完成此操作

如果您不使用任何捆绑器,请考虑使用 javascript 而不是 JSON,因为 JSON 是 Javascript Object Notation,唯一的区别是 JSON 是简单的字符串(你可以解析)。

所以直接使用javascript,不用任何JSON.parse

如果您需要使用 json formats,您可以通过 Javascript...

加载它们

看看https://blog.gospodarets.com/fetch_in_action fetch('/path/to/locale/en.json).then(res => res.json()).then(translations => console.log('translations', translations));

我找到了一个非常巧妙的解决方案:ember-cli-json-module

安装此插件后,我可以做:

// master.json:
{
  "back": "Back",
  "or": "Or",
  "cancel": "Cancel"
}

// translations.js:
import masterFile from './master';

export default masterFile;

我还删除了 EcmaScript6 标签,因为这是一个专门的 ember-cli 解决方案。