Pass environment variable into a Vue App at runtime

后端 未结 5 1394
孤街浪徒
孤街浪徒 2020-12-05 17:34

How can I access environment variables in Vue, that are passed to the container at runtime and not during the build?

Stack is as follows:

  • VueCLI 3.0.5
5条回答
  •  时光说笑
    2020-12-05 18:33

    Create config file

    In public folder: public/config.js

    const config = (() => {
      return {
        "VUE_CONFIG_APP_API": "...",
      };
    })();
    

    Update index.html

    Update public/index.html to contain following at the end of head:

      
      
    

    There is no need to update vue.config.js as we are using the public folder for configuration.

    ESLint

    ESLint would give us error of usage of undefined variable. Therefore we define global variable in .eslintrc.js file:

      globals: {
        config: "readable",
      },
    

    Usage

    Eg. in the store src/store/user.js

    export const actions = {
      async LoadUsers({ dispatch }) {
        return await dispatch(
          "axios/get",
          {
            url: config.VUE_CONFIG_APP_API + "User/List",
          },
          { root: true }
        );
      },
    ...
    

    K8S ConfigMap:

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: fe-config
      namespace: ...
    data:
      config.js: |
        var config = (() => {
          return {
            "VUE_CONFIG_APP_API": "...",
          };
        })();
    

    Deployment

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      ...
    spec:
      ...
      template:
        ...
        spec:
          volumes:
            - name: config-volume
              configMap:
                name: fe-config
          containers:
            - ...
              volumeMounts:
                    - name: config-volume
                      mountPath: /usr/share/nginx/html/config.js
                      subPath: config.js
    

提交回复
热议问题