【问题标题】:Adding configuration to Webpack-based SPA向基于 Webpack 的 SPA 添加配置
【发布时间】:2017-12-30 21:56:49
【问题描述】:

我正在使用 Vue.js 和 Webpack 2 编写 SPA。Node 生态系统对我来说是相当新的体验。

我需要能够设置一些配置变量,最好是动态解析。在我看来,该解决方案将涉及在加载应用程序时获取的配置文件。这个问题看起来很笼统,但我没有设法用谷歌搜索类似的东西。

在 Webpack 世界中是否有任何“标准”解决方案,或者至少有任何既定的良好实践?

【问题讨论】:

    标签: javascript node.js webpack webpack-2


    【解决方案1】:

    假设您将配置变量存储在 JSON 文件 config.json 中。

    {
      "some": "123",
      "configs": "456",
      "here": "789"
    }
    

    在您的应用程序中要求您的配置文件带有文件加载器。 https://github.com/webpack-contrib/file-loader

    // Require config file
    // File-loader returns the public URL for your file required here
    var configURL = require("file-loader!./config.json");
    

    在初始化 Vue 应用程序之前,使用简单的 XHR 加载 config.json。

    // Create XHR
    var configXHR = new XMLHttpRequest();
    configXHR.open("GET", configURL, false);    // Synchronous request
    configXHR.send();
    
    // Response status check
    if(configXHR.status == 200) {
      var configs = JSON.parse(configXHR.responseText);
      console.log(configs);
    } else {
      throw "Unable to load config file";
    }
    
    // Bootstrap your Vue application below
    // ...
    

    【讨论】:

      【解决方案2】:

      最好动态解决

      一个简单的解决方案可能依赖于HMR,它允许加载和动态更新导入的资源。还有更多,Webpack + HMR 会在服务器上自动监视文件,如果发生,会在客户端发布更新。

      流派经典 - https://webpack.js.org/concepts/hot-module-replacement/

      import config from 'APP_CONFIG';
      // Some code ...
      if(module.hot) {
        module.hot.accept('APP_CONFIG', () => {
        // Reaction to changes...
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-09
        • 1970-01-01
        • 2018-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多