Vue Cli下环境变量和模式
Vue Cli下环境变量和模式
一. 模式
Vue Cli 项目中有三种模式:development(开发模式)、production(生产模式)、test(测试模式)。注意模式不同于NODE_ENV,一个模式可以包含多个环境变量。
1. 通过pageage.json下scripts配置打包命令。
development: 对应的命令 vue-cli-service serve
production:对应的命令 vue-cli-service build 和 vue-cli-service test:e2e
test:对应的命令 vue-cli-service test:e2e
{
"name": "vue-cli3-app",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"dev": "vue-cli-service serve",
"build": "vue-cli-service build",
"build:prod": "vue-cli-service build --mode production --modern",
"build:dev": "vue-cli-service build --mode development --modern",
"lint": "vue-cli-service lint"
},
}
2. 修改项目模式
可以通过传递 --mode 选项参数为命令行覆写默认的模式:vue-cli-service build —mode developments
二. 环境变量
一个环境文件只包含环境变量的“键=值”对。
特定模式准备的环境文件将会比一般的环境拥有更高的优先级。
.env # 在所有的环境中被载入
.env.local # 在所有的环境中被载入,但会被 git 忽略
.env.[mode] # 只在指定的模式中被载入
.env.[mode].local # 只在指定的模式中被载入,但会被 git 忽略
// .vue.production文件
name=生产环境下变量
auth=释放自己的情绪
// vue.config.js文件
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
const debugUrl = process.env.NODE_ENV === 'production' ? 'https://prod-baidu.com' : 'https://test-baidu.com'
module.exports = {
pages: {
index: {
// entry for the page
entry: 'src/main.js',
// the source template
template: 'public/index.html',
// output as dist/index.html
filename: 'index.html'
}
},
lintOnSave: true,
// 链式操作
chainWebpack: (config) => {
config.resolve.alias
.set('@', resolve('src'))
.set('assets', resolve('src/assets'))
},
configureWebpack: config => {
console.warn('\nwebpack---begin')
if (process.env.NODE_ENV === 'production') {
// 生产环境
console.log('\n生产模式下:', debugUrl, '\n生产模式下环境变量:', process.env.name, process.env.auth)
} else {
// 开发环境
console.log('\n开发模式下:', debugUrl, '\n开发模式下环境变量:', process.env.name)
}
console.log('webpack---end')
},
devServer: {
port: 5200,
proxy: {
'/*.json': {
target: debugUrl
},
'/*.do': {
target: debugUrl
},
'/*.m': {
target: debugUrl
}
}
}
}
Vue Cli下环境变量和模式相关教程