1

I have a translations file at:

frontend/locales/en/translations.js

which looks like:

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

I want to move the translations hash into a .json file:

frontend/locales/en/translations.json

and somehow include it in the .js file.

What's the best way to do this?

yuяi
  • 2,617
  • 1
  • 23
  • 46

2 Answers2

2

I found a pretty slick solution: ember-cli-json-module.

After installing this add-on, I can do:

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

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

export default masterFile;

I also removed the EcmaScript6 tag, as this is a specifically ember-cli solution.

yuяi
  • 2,617
  • 1
  • 23
  • 46
0

EcmaScript 6 modules don't allow to import .json (or something else), they are focused on javascript only.

this is a reference: How to import a json file in ecmascript 6?

You can do it using some bundler like webpack that has a specific json-loader.

If you don't use any bundler, consider to use javascript instead of JSON, because JSON is a Javascript Object Notation, the only difference is that JSON is simple string (that you can parse).

So use javascript directly without any JSON.parse.

If you need to use json formats you can load them via Javascript...

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

Community
  • 1
  • 1
Hitmands
  • 13,491
  • 4
  • 34
  • 69
  • 1
    *"EcmaScript 6 modules don't allow to import .json (or something else), they are focused on javascript only."* Ultimately it's the module loader that does or does not support loading of non-JavaScript files. ES6 modules only provide a specification for syntax and (some) semantics. How module identifiers are resolved depends on the environment. E.g. `import Foo from './bar.json'` in Node (given, of course, that you transpile `import` to `require`), because Node allows to load JSON files. – Felix Kling Mar 28 '16 at 18:55