Search code examples
javascriptjsonframeworksaureliadistribute

JavaScript Single-Page-App - how do i "distribute" a json?


I'm currently using the Aurelia-Framework and want to load a big json file into my application.

The problem is, I cant figure out how to get the json file to appear in the "dist" folder of my Chrome browser so that the script is able to find it.

In short, I want to do this:

var request = new XMLHttpRequest();
var jsonString = request.open("GET", "file://../core/data/5e-SRD-Monsters.json", false);

...and yes, the path is correct but the folder "data" and its content won't appear in Chrome's debug sources.

Do I have to include the json via gulp somehow?


Solution

  • Your main question is "how to get the json file to appear in the 'dist' folder". As also mentioned in the comments, that is a matter of simply includ.

    For a skeleton jspm project do the following:

    1. Open the ~/build/export.js file
    2. Include the file, or folder, containing the .json file in the first 'list' section

    This looks something like:

        module.exports = {
          'list': [
            'index.html',
            'config.js',
            'favicon.ico',
            'LICENSE',
            "jspm_packages/npm/[email protected]/js/browser/bluebird.min.js", 
            'jspm_packages/system.js',
            'jspm_packages/system-polyfills.js',
            'jspm_packages/system-csp-production.js',
            'styles/styles.css',
            'core/data/5e-SRD-Monsters.json'
          ],
    

    Here is an an example on where to put it.

    Important: Considering you're talking about a 'dist' folder I am assuming you use the skeleton with jspm. The process is totally different when you're building an Aurelia app built with CLI, skeleton webpack or perhaps the starter kit.

    Now you've got the .json file in the dist folder. But using the XMLHttpRequest to load a file:// isn't exactly the recommended approach. As also mentioned in the comments, ideally you should load it up as a http request, not a file request.

    Let's take this into advice. All you need to do is add the aurelia-fetch-client to your library and then you can simply do something like this:

    import { HttpClient } from 'aurelia-fetch-client';
    
    export class App {
    
      get_stuff() {
        let http = new HttpClient();
    
        // assuming the file is in /dist/core/data/,
        // simply read it through a promise + through a relative path:
        http.fetch('./core/data/5e-SRD-Monsters.json')
            .then(data => console.log(data));
      }
    
    }
    

    Now this uses http rather than file://, which will eliminate any permission issues that might occur, such as lack of access to the filesystem directly.