How to configure environment variables with vue-cli 3?

Viewed 14231

i try to use environment variables in vue-cli, but is not working, everytime says 'undefined' when use console.log(process.env.VUE_APP_BASE_URI). But process.env.NODE_ENV says 'development' as i defined in webpack.config.js.

I read the documentation of vue-cli 3 and put my .env.* files in the root project. like this: enter image description here

Webpack.config.js

    module.exports = {
  mode: 'development',
  context: __dirname,
  entry: {
    main: ['babel-polyfill', './App/index.js']
  },
  plugins:[
    new VueLoaderPlugin()
  ],

.env.development

VUE_APP_BASE_URI=http://localhost:64208/api/

.env.production

VUE_APP_BASE_URI=http://localhost:64208/api/

I use .NET Core with Vue. How to use the environment?

5 Answers

it just happened to me, the solution is very simple. Just restart your development server.

ctrl + c

then

npm run serve

There might be different ways to achieve this, one easy way from command line would be:

npx vue-cli-service serve --mode production

Default to development if mode was not specified.

You need to rename the file to .env only instead of .env.production or .env.development. it should work, if not, comment on the same thread.

I do not know if this is the same problem that you had, but this happend in my case:

  • I set up everything correct as you did (Not any .config.js file)
  • I then stopped and startet the dev-server with npm run serve
  • When I now refreshed the page, nothing changed in the console

Then I saw that the npm run serve command had started the site on a different port!. The old version was still running, but gave the old values. When I tried the new port the values where correct.

In my case (Vue CLI 3 with Core 2.2) I have to put the .env files under the Core webapp folder. It did not work if I have them in wwwroot or the Vue app folder.

enter image description here

Related