0
votes

Given that ember-cli uses ES6 modules syntax to import other JavaScript files, is it also possible to use this same syntax to import non-JavaScript files, such as JSON files or other text files?

Assume I have a JSON file named "foo.json" in my current directory. How could I import the contents of that file into a variable within my current JavaScript file? I've tried, without success, several variations of:

import foo from 'foo.json';

if (typeof foo === 'object') {
  // Success
} else {
  // import failed
}

Is it possible to import non-JavaScript files into the current file using the import statement or any other means?

2

2 Answers

2
votes

No it's not. The ES6 modules syntax to import stuff also needs the requested object to be properly exported, which your json-files or text-files won't be. Also, since we don't really have ES6 in browsers yet, all those nifty statements are converted to commonjs-modules when building your project.

As I see it you have two options for this.

Putting the files in your public-folder and load them via ajax is the simple solution though not very elegant.

The cool option would be to add a preprocessor of your own that wraps your json-files in a proper export-statement as a build-step. That would be quite a lot of more work though and might require some deep diving into ember-cli and broccoli to attach it at the right time.

2
votes

Yes, ember-cli can import JSON and non-JS files as long as you have the proper plugin.

This one allows the import of JSON files: https://github.com/IvyApp/ember-cli-json-module

... and this one works for YAML: https://github.com/joankaradimov/ember-cli-yaml-module.