How to overwrite environment variables in Vue-cli3?

Viewed 1984

Let us assume we have a Vue.js project build with Vue-cli3 , package.json:

{ "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", ... }

Also, we have a plan to push our project to a public repository on GitHub, so we need different environment variables for public repo and for the local development. Vue-cli 3 gives us modes: https://cli.vuejs.org/guide/mode-and-env.html#modes

I have such a files:

  • .env
  • .env.development
  • .env.production
  • .env.local
  • .env.development.local
  • .env.production.local

Content of .env:

NODE_ENV=production VUE_APP_PATH=http://website.com/ VUE_APP_API_ROUTE=api/v1/

Content of .env.development:

NODE_ENV=development VUE_APP_PATH=http://dev-website.com/

Content of .env.development.local:

NODE_ENV=development VUE_APP_PATH=http://localhost:8080/

When I do npm run serve I expect process.env.VUE_APP_PATH will be equals http://localhost:8080/ but unfortunately it stills = http://dev-website.com/. So, the problem is variables from local env files (i.e. .env.development.local) are not overwrite existed from another env file (i.e. .env.development).

How can I use this vue-cli approach to overwrite neccessary variables? The documentation tells about priority: An env file for a specific mode (e.g. .env.production) will take higher priority than a generic one (e.g. .env). but with .local files it doesn`t work.

1 Answers

You can pass in the --mode option within the npm script. So, in your instance you might want the serve script to look like:

vue-cli-service serve --mode development.local

If you wanted to test out serving your non-local development configuration you could copy the serve script and rename it serve:local and then edit the original serve script to look like this:

vue-cli-service serve --mode development

Which is really the actual default mode for serve out-of-the-box with CLI 3. We've just explicitly set the mode.

Related