Vue CLI - Keep config file as external after compilation

巧了我就是萌 提交于 2020-01-23 01:30:06

问题


I'm developing an application with Vue CLI. This application is a web interface which will have to communicate with a Rest API on a board.

So, because the board will move, the IP of the board will change over time depending on where I am.

This is my project current tree :

The IP configuration is contained in the Settings.js file :

export const Settings = {
    // Server configuration
    SERVER_IP: '127.0.0.1',
    SERVER_PORT: '9000',

    SERVER_PROTOCOL: 'http', // http or https

    // Website configuration
    DEBUG_MODE: true
};

And in my files, I import this IP with the following statement :

import {Settings} from '../../Settings'
const ip = Settings.SERVER_IP;

// Do stuff

This works fine. But the problem is: I have to recompile everything when the IP change. Because Settings.js is compiled with other JS files.

So, I would like to know if there is a way to have a config file which will remain in the dist/ directory and will be read by my JS application during execution. So I will not have to recompile everything each time my application server IP change.

Ty for your help :)


回答1:


My solution for Vue is based on solution for Angular.

You can have an environment variables exactly like backend developers use.

But the difference is that backend code executed inside the server while frontend code is nothing but files on the disk that you withdraw as static without giving them even a chance to run and check env vars before being withdrew.

But your code is being executed inside the browser. So this is the ideal and the only proper place to have an env.

However, you have to prepare this env beforehand - according to your backend env.

Here is the plan:

  1. You exclude from compilation your settings file (see below).
  2. Your settings file "constructs" the env before you run the Vue app.
  3. From your code you use that env and, also, you can update this env in runtime.

So here is your final code structure:

root_project_dir:
├─> cfg
│   └── settings.js
├─> public
│   ├── favicon.ico
│   └── index.html
├─> src
│   ├── App.vue
│   ├─> assets
│   │   └── logo.png
│   ├─> components
│   ├─> layouts
│   ├── main.js
│   ├─> plugins
│   ├─> router
│   ├─> store
│   └─> views
└── vue.config.js

Create settings file cfg/settings.js:

/*
This file goes as an asset without any of compilation even after build process.
Thus, it can be replaced in a runtime by different file in another environment.

Example for Docker:
  docker run -v ./local_cfg_dir:cfg image:tag
*/

(function(window) {
  window.__env = window.__env || {};

  window.__env.api = {
    "url": "http://127.0.0.1:8000",
    "timeout": 80000
  };
  window.__env.captcha = {
    "enabled": true,
    "key": "Mee1ieth1IeR8aezeiwi0cai8quahy"
  };
  window.__env.rollbar = {
    "enabled": true,
    "token": "zieriu1Saip5Soiquie6zoo7shae0o"
  };
  window.__env.debug = true;
})(this);

Provide Webpack with the instruction to copy cfg files during npm run build stage in vue.config.js (you can't change this name):

module.exports = {
  chainWebpack: config => {
    config.plugin("copy").tap(([pathConfigs]) => {
      const to = pathConfigs[0].to;
      pathConfigs[0].force = true; // so the original `/public` folder keeps priority

      // Other locations.
      pathConfigs.unshift({
        from: "cfg",
        to: "cfg"
      });

      return [pathConfigs]})
  },
  transpileDependencies: ["vuetify"]
};

Now, when you build the project you will see it in the resultant dir:

dist
 ├─> cfg
 │   └── settings.js
 ├─> css
 │   ├── app.06b1fea6.css
 │   └── chunk-1f2efba6.a298b841.css
 ├── favicon.ico
 ├─> img
 │   └── logo.09e0e4e1.png
 ├── index.html
 └─> js
     ├── app.8fc75c19.js
     ├── app.8fc75c19.js.map
     └── chunk-vendors.1ab49693.js.map

So you can run this setup in public/index.html before you run app in the same window:

  <body>
    <div id="app"></div>
    <script src="/cfg/settings.js"></script>
    <!-- built files will be auto injected -->
  </body>

Now you have it in your window:

And from any place in the code you can reach this env:

Vue.use(VueReCaptcha, { siteKey: window.__env.captcha.key })

Sidenote:

If you want to be "DevOps-compatible" you need to have a settings in a nested directory (cfg in our example). This will give an ability to make mounts in Kubernetes/Swarm without overwriting entire directory of dist.




回答2:


Do you know the complete list of IP addresses in advance? If so you can create a function that returns the correct IP based on whatever time/location logic.

Otherwise you can try moving the settings file to the public folder, add to your .gitignore file, making sure you reference it in your public/index.html. It will now sit outside of the compiled Vue app and can be accessed from within Vue as a global settings variable.

So instead of import {Settings} from '../../Settings' you would reference window.Settings

e.g. const ip = window.Settings.SERVER_IP;

This way you can edit the settings directly without having to recompile each time.




回答3:


you can create a config.json file in public directory and then in main js you can fetch it and load the config file. Now your dist created with this config.json.

fetch('/config.json').then(res => res.json()).then(config => {
     .......
})


来源:https://stackoverflow.com/questions/54004759/vue-cli-keep-config-file-as-external-after-compilation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!