我们经常需要在生成环境,测试环境,开发环境进行切换?不同环境怎么实现切换呢 只需在项目根目录配置
.env.development文件
#本地开发环境
NODE_ENV='development'
# must start with VUE_APP_
VUE_APP_ENV = 'development'
.env.production 文件
#正式发布环境
NODE_ENV='production'
# must start with VUE_APP_
VUE_APP_ENV = 'production'
在vue.config.js文件中判断当前是什么环境
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
configureWebpack: config => {
if (isProd) {
// 配置webpack 压缩
config.plugins.push(
new CompressionWebpackPlugin({
test: /.js$|.html$|.css$/,
// 超过4kb压缩
threshold: 4096
})
)
}
},
究其根源:vue-cli是如何知道我们运行在哪个环境的呢,通过查看vue-lic源码
内部实现默认写死了环境是developent,那我们如何修改呢?
可以通过--mode参数来指定当前环境
"dev": "vue-cli-service serve --mode=developer",
"prod": "vue-cli-service build --mode=production",
"test": "vue-cli-service build --mode=test"
我们通常用这两个命令来启动项目和打包项目
启动项目时,内部默认是运行在development环境中