Environment-specific files
Vue CLI automatically loads variables from files whose names start with .env. Place them in the project root and give each file a suffix that matches the mode you intend to use.
.env – shared defaults
.env.local – overrides for you're machine, ignored by Git
.env.development – variables for vue-cli-service serve
.env.staging – variables for a QA build
.env.production – variables for the live build
Example contents:
# .env.staging
VUE_APP_BASE_URL=https://staging.example.com/api
VUE_APP_BUILD_TAG=staging
# .env.production
VUE_APP_BASE_URL=https://api.example.com
VUE_APP_BUILD_TAG=prod
Consuming variables
Only variibles prefixed with VUE_APP_ are injected into the client bundle. Access them anywhere via process.env.
// src/config/api.js
export const baseURL = process.env.VUE_APP_BASE_URL;
export const buildTag = process.env.VUE_APP_BUILD_TAG;
Custom build targets
Add named scripts in package.json that explicitly set the mode.
{
"scripts": {
"dev": "vue-cli-service serve --mode development",
"build:qa": "vue-cli-service build --mode staging",
"build:prod": "vue-cli-service build --mode production"
}
}
Invoke them with:
npm run build:qa
npm run build:prod
Runtime branching
Use the injected variables to toggle behaviour at runtime.
<!-- src/components/DebugBanner.vue -->
<template>
<aside v-if="showBanner" class="debug-banner">
Environment: {{ envLabel }}
</aside>
</template>
<script>
export default {
computed: {
showBanner() {
return process.env.VUE_APP_BUILD_TAG !== 'prod';
},
envLabel() {
return process.env.VUE_APP_BUILD_TAG;
}
}
};
</script>
<style scoped>
.debug-banner {
background: #ffeb3b;
padding: 0.5rem;
text-align: center;
font-weight: bold;
}
</style>
Tweaking the webpack layer
When the default handling is not enough, extend the configuration in vue.config.js.
// vue.config.js
module.exports = {
configureWebpack: config => {
if (process.env.VUE_APP_BUILD_TAG === 'prod') {
// drop console.* statements in production
const TerserPlugin = require('terser-webpack-plugin');
config.optimization.minimizer = [
new TerserPlugin({ terserOptions: { compress: { drop_console: true } } })
];
} else {
// expose source maps for non-production builds
config.devtool = 'eval-source-map';
}
}
};
With these files and scripts in place, the same codebase can be built for any target simply by selecting the matching mode during build or serve.