Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue & Webpack: Global development and production variables

I'm using vue-cli to build my web app. My app uses an api in a number of places like so:

axios.post(API + '/sign-up', data).then(res => {
  // do stuff
});

The API variable is a constant containing the beginning of the address, e.g., https://example.com.

How would I detect whether this is a dev or prod build and set that variable accordingly? For now, I have a script tag in my index.html document and I am manually changing it for dev and prod:

<script>var API = 'https://example.com'</script>

Is there a better way to handle this?

like image 415
Glenn Avatar asked Jan 28 '26 02:01

Glenn


1 Answers

If you're using the vue-cli webpack template, within the config folder you'll see two files: dev.env.js and prod.env.js.

Both files contain an object that is globally available throughout your Vue app:

dev.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})

prod.env.js

module.exports = {
  NODE_ENV: '"production"'
}

Note that string values require the nested single and double quotes. You can add your own variables like so:

dev.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API: '"http://localhost:8000"'
})

prod.env.js

module.exports = {
  NODE_ENV: '"production"',
  API: '"https://api.example.com"'
}

Now the variable can be accessed within any Vue method from the process.env object:

process.env.API
like image 158
Glenn Avatar answered Jan 29 '26 15:01

Glenn