JavaScript 单页应用程序 - 如何 "distribute" 成为 json?

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

我目前正在使用 Aurelia-Framework 并想将一个大 json 文件加载到我的应用程序中。

问题是,我不知道如何让 json 文件出现在我的 Chrome 浏览器的 "dist" 文件夹中,以便脚本能够找到它.

简而言之,我想这样做:

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

...是的,路径正确,但文件夹 "data" 及其内容不会出现在 Chrome 的调试源中。

我是否必须通过 gulp 以某种方式包含 json?

您的主要问题是"how to get the json file to appear in the 'dist' folder"。正如评论中也提到的那样,这只是简单地包含的问题。

对于 skeleton jspm 项目执行以下操作:

  1. 打开 ~/build/export.js 文件
  2. 在第一个 'list' 部分中包含包含 .json 文件的文件或文件夹

这看起来像:

    module.exports = {
      'list': [
        'index.html',
        'config.js',
        'favicon.ico',
        'LICENSE',
        "jspm_packages/npm/bluebird@3.4.1/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'
      ],

这是 an an example 放在哪里。

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.

现在您在 dist 文件夹中有了 .json 文件。但是使用 XMLHttpRequest 加载 file:// 并不是推荐的方法。如评论中所述,理想情况下,您应该将其加载为 http 请求,而不是文件请求。

让我们把这个作为建议。您需要做的就是 将 aurelia-fetch-client 添加到您的图书馆,然后您可以简单地执行以下操作:

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));
  }

}

现在使用 http 而不是 file://,这将消除可能发生的任何权限问题,例如无法直接访问文件系统。