Using Environment Variables with Vue.js

后端 未结 9 1411
礼貌的吻别
礼貌的吻别 2020-11-29 18:22

I\'ve been reading the official docs and I\'m unable to find anything on environment variables. Apparently there are some community projects that support environment variabl

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 18:51

    If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.

    The variables will automatically be accessible under process.env.variableName in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.

    You have a few options, this is from the Environment Variables and Modes documentation:

    .env                # loaded in all cases
    .env.local          # loaded in all cases, ignored by git
    .env.[mode]         # only loaded in specified mode
    .env.[mode].local   # only loaded in specified mode, ignored by git
    

    Your .env file should look like this:

    VUE_APP_MY_ENV_VARIABLE=value
    VUE_APP_ANOTHER_VARIABLE=value
    

    It is my understanding that all you need to do is create the .env file and add your variables then you're ready to go! :)

    As noted in comment below: If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

    Don't forget to restart serve if it is currently running.

提交回复
热议问题