Vue-cli: Environment Variables

Created on 5 Feb 2018  路  35Comments  路  Source: vuejs/vue-cli

How can I configure my environment variables in this new cli? For example, BASE_URL, ENDPOINT_API?

Thanks.

Most helpful comment

As Evan just told you: Use a .env file. If you don't know what that is - it's a file named .env, in your project's root directory, that contains env variables just like you write them in your terminal:

I know what is that.

Actually, .env file just allow variables that starts with VUE_APP_ ;)

All 35 comments

Hello, your issue has been closed because it does not conform to our issue requirements. In order to ensure every issue provides the necessary information for us to investigate, we require the use of the Issue Helper when creating new issues. Thank you!

Use .env files. Variations like .env[.mode][.local] are also supported. Also, only variables starting in VUE_APP_ will be available in the app.

There will be more documentation on this soon.

Thanks dude,

But how can I replace BASE_URL?

There will be more documentation on this soon.

As Evan just told you: Use a .env file. If you don't know what that is - it's a file named .env, in your project's root directory, that contains env variables just like you write them in your terminal:

BASE_URL=http://google.com/

BASE_URL should be configured in vue.config.js, since it's also needed by the cli-service:

module.exports = {
  baseUrl: '/foo'
}

As Evan just told you: Use a .env file. If you don't know what that is - it's a file named .env, in your project's root directory, that contains env variables just like you write them in your terminal:

I know what is that.

Actually, .env file just allow variables that starts with VUE_APP_ ;)

Hello,
Regarding to the ENV I would like to use in the app some variables from Jenkins for example.

When in vue.config.js I do console.log('Commit:', process.env.GIT_COMMIT) I get it correctly.

In .vue files process.env is only replaced by

Object({
   NODE_ENV: "production"
})

I read about the .env but I don't know how to put _variables_ there. What is the correct way to do it?

Thanks

Thanks @phoet in the end I made it work with the change below in vue.config.js

module.exports = {
  configureWebpack: {
    ...,
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'GIT_COMMIT': JSON.stringify(process.env.GIT_COMMIT),
          'GIT_BRANCH': JSON.stringify(process.env.GIT_BRANCH)
        }
      })
    ]
  }
}

And then using it like process.env.GIT_COMMIT in some .js

I have done another thing that probably is not really good but it works too.

In package.json:

"scripts": {
  "build": "VUE_APP_ANNOTATION_VERSION=$(npm run --silent getAnnotationVersion) vue-cli-service build",
  "getAnnotationVersion": "node ./custom-script.js'"
},

And in custom-script.js

const {readFile} = require('fs');

function getAnnotationVersion() {
  readFile('../version.py', 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }
    let reg = /.*VERSION.+'(.*)'/;
    let found = data.match(reg);
    if (found.length > 1) console.log(found[1]);
  });
}

getAnnotationVersion();

@yyx990803 Dear Evan, after reaching to this issue report, I realized BASE_URL needs to be configured in vue.config.js not in .env. The problem has been solved. Thank you very much.

I'm also think, the README is a bit misleading. Do you think it would be easier, if Vue client could internally first looks vue.config.js, and also looks any exiting .env and take environment variables from there automatically?

Does support for .env[mode][local] require we add dotenv library? I have a .env.development file in my app root with an environment variable using the VUE_APP_ prefix and it does not get loaded.

No dotenv required I see: https://github.com/vuejs/vue-cli/blob/dd39866cad4385b284782428abcbd554f131e1ab/packages/%40vue/cli-service/lib/Service.js#L58

Sorry, I was not running with the right mode to load my .env.development file. ie vue-cli-service test:e2e --mode development

I've been looking for this information around but could not find it.

If I create a real env variables (during my Gitlab pipeline for example) such as VUE_APP_API_URL, will this variable take priority from the .env files ?

.env files should never contain sensible data, and thus sensible data should be provided by Jenkins/Gitlab/etc. It's not clear if the .env file from vue are working like dotenv ones

Existing env variables have highest priority.

Sadly, after testing it seems it is not the case.

echo "$VUE_APP_API_URL" will give me the correct output before a yarn build, so I would expect the variable to be correctly replaced in the build.

We need this in DOC 馃

@RDeluxe Hard to make anything from such a blanket statement. Can you provide a reproduction?

Also, maybe you simply aren't on the latest version? We only fixed this in the last beta before RC or something.

@cbo317110 That would make sense, yet.

Sorry. The repro is quite simple :

  • Create an .env file with a variable, such as VUE_APP_VAR = myvar
  • Add it to the webpack defines in vue.config.js. For now it's fine
  • Define an env variable (ie in windows SET VUE_APP_VAR = mysecondvar)
  • Build, and check. For me, it was still equals to myvar

We are using 3.0.0-beta.15

Add it to the webpack defines in vue.config.js. For now it's fine

You shouldn't do this.

Add it to the webpack defines in vue.config.js. For now it's fine

We introduced .env file so you don't have to do this, why would you?

We are using 3.0.0-beta.15

... and we changed priority for env variables in beta.16:

https://github.com/vuejs/vue-cli/blob/dev/CHANGELOG.md#300-beta16-2018-06-08

  • env: preserve existing env vars so load in reverse order. (#1503) (7c1ef24)

Sorry, just a reflex, does not change anything in the end I guess, but the behavior was the same anyway, and it seems the explanation was simply the version we were using ! Thanks.

We are deploying vue-cli3 app od Digital Ocean trough Laravel Forge and the .env variables are not read. Locally in development environment works fine but on the DO server not. Anyone knows what is the issue?

We have followed this guide as well https://alligator.io/vuejs/using-new-vue-cli-3/#environment-variables but we can not find the solution.

UPDATE: we have now reconfigured NGINX website eon the production server to show to dist instead to public folder. Now .env is read properly. Not sure why this matter... Can anyone explain?

Thanks @phoet in the end I made it work with the change below in vue.config.js

module.exports = {
  configureWebpack: {
    ...,
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'GIT_COMMIT': JSON.stringify(process.env.GIT_COMMIT),
          'GIT_BRANCH': JSON.stringify(process.env.GIT_BRANCH)
        }
      })
    ]
  }
}

And then using it like process.env.GIT_COMMIT in some .js

This worked really well for me..But it would be great if there's a way in which variables can be directly read from .env file.

But there is, we have a big section about it in the docs

We need this in DOC 馃

Now it's in the doc.see here.Thanks @LinusBorg for letting me know about that.

It has always been in the docs.

I have the following in a .env file in the root of my project

VUE_APP_SERVER_URI = http://localhost:3333/api/v1
VUE_APP_SERVER_URL = TestString

When I do console.log(process.env) in my App.vue file, I don't see the variables

This is the output

{NODE_ENV: "development"}
NODE_ENV: "development"
__proto__: Object

Any idea why vue might not be loading my environment variables?

I have the following in a .env file in the root of my project

VUE_APP_SERVER_URI = http://localhost:3333/api/v1
VUE_APP_SERVER_URL = TestString

When I do console.log(process.env) in my App.vue file, I don't see the variables

This is the output

{NODE_ENV: "development"}
NODE_ENV: "development"
__proto__: Object

Any idea why vue might not be loading my environment variables?

I am having the same issue. It's getting a little frustrating

I have the following in a .env file in the root of my project

VUE_APP_SERVER_URI = http://localhost:3333/api/v1
VUE_APP_SERVER_URL = TestString

When I do console.log(process.env) in my App.vue file, I don't see the variables
This is the output

{NODE_ENV: "development"}
NODE_ENV: "development"
__proto__: Object

Any idea why vue might not be loading my environment variables?

I am having the same issue. It's getting a little frustrating

Didn't you try this? https://github.com/vuejs/vue-cli/issues/787#issuecomment-390899673

@yyx990803 Hey Evan, how can I tell my vue.config.js to change the precedence of the .env variables? I want to set that .env.local and/or .env.[mode].local have the highest priority and if the same variable is defined elsewhere, it'd be ignored.

Is this possible?

Reason: I want to use .env for the production environment, .env.development for the development environment (duh) and locally while "developing" to pass some extra and some override variables within .env.local

EDIT:

So, I found this @vue/cli-service/lib/Service.js, specifically method loadEnv. I read how it works and noticed that it first loads .env.local and afterwards the .env.development. _(for example, mode is an argument)_

From this, I could clearly see that there's no easy way to make .env.local take priority.
Here's my solution... _(it does not care about any possible .env.[mode].local options, as I don't personally need it)_

// vue.config.js

const path = require('path')
const dotenv = require('dotenv')

const localEnv = dotenv.config({
  path: path.resolve(__dirname, '.env.local')
})

const stringifyValues = input => {
  const output = {}

  for (const key in input) {
    output[key] = JSON.stringify(input[key])
  }

  return output
}

module.exports = {
  chainWebpack: config => {
    config
      .plugin('define')
      .tap(args => {
        Object.assign(args[0]['process.env'], stringifyValues(localEnv.parsed))
        return args
      })
}

It does exactly what I wanted, but not sure if there's a cleaner or better approach. Please let me know, whoever sees this and @ at me! Thanks!

I tried this [#787 (comment)(https://github.com/vuejs/vue-cli/issues/787#issuecomment-390899673) but it was not working....

I tried to stop node server and restarted node server...

npm run serve

of course, after editing vue.config.js and it is working fine...

You can take a look at following and write your own chainWebpack.

https://github.com/vuejs/vue-cli/blob/eaa2b73/packages/@vue/cli-service/lib/Service.js#L90-L106
https://github.com/vuejs/vue-cli/blob/01e36f3/packages/@vue/cli-service/lib/util/resolveClientEnv.js
https://github.com/vuejs/vue-cli/blob/5bf6051/packages/@vue/cli-service/lib/config/base.js#L192-L197

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brandon93s picture brandon93s  路  3Comments

Gonzalo2683 picture Gonzalo2683  路  3Comments

eladcandroid picture eladcandroid  路  3Comments

OmgImAlexis picture OmgImAlexis  路  3Comments

miyamoto-san picture miyamoto-san  路  3Comments