Loading JSON Files in Aurelia

At the time of writing this, the preferred approach to client side dependencies and loading is Jspm which is one part package manager and one part SystemJS loader polyfill.

Although, we will be seeing other loader options in the near future such as Webpack and even a potential custom loader from the Aurelia team. But for now we have Jspm and System.js.

Install the JSON loader for System.js

We can use the JSON loader for System.js to load JSON files in our app in a bulletproof way. You can view the plugin here and see that it is really quite simple under the hood.

To install it in your application, ensure you have run npm install and jspm install for your previous dependencies. Then install the JSON plugin by running: jspm install json

Then you can use it in your Aurelia application like-so:

import * as myJson from 'jsonfile.json!json';

Notice we use the wildcard * and the as keyword? This is because if a file has no default export, we essentially have to create one. There might be other ways to include JSON such as using require but we will stick to using import for the sake of this article.

Conclusion

That’s it. There is nothing complex here. Simply install the loader plugin for System.js and the rest takes care of itself. Things to remember are your JSON files need to be properly formatted as JSON or you will encounter issues.