vue多环境变量配置
package.json
里的 scripts
配置 不同环境选下的不同命令,
"scripts": {
"serve": "vue-cli-service serve --open",
"stage": "vue-cli-service build --mode staging",
"build": "vue-cli-service build",
}
在项目根目录中新建.env.
文件
- .env.development 本地开发环境配置
NODE_ENV='development'
// must start with VUE_APP_
VUE_APP_ENV = 'development'
- .env.staging 测试环境配置
NODE_ENV='production'
// must start with VUE_APP_
VUE_APP_ENV = 'staging'
- .env.production 正式环境配置
NODE_ENV='production'
// must start with VUE_APP_
VUE_APP_ENV = 'production'
新建config文件夹 盛放index.js,env.development.js等文件
修改起来方便,不需要重启项目,符合开发习惯。
配置对应环境的变量,拿本地环境文件env.development.js
举例
// 本地环境配置
module.exports = {
title: 'vue-h5-template',
baseUrl: 'http://localhost:9018', // 项目地址
baseApi: 'https://test.xxx.com/api', // 本地api请求地址
APPID: 'xxx',
APPSECRET: 'xxx'
}
根据环境不同baseUrl就会不相同
// 根据环境不同引入不同baseApi地址
import { baseApi } from '@/config'
console.log(baseApi)
以 VUE_APP_ 开头的变量,在代码中可以通过 process.env.VUE_APP_ 访问
rem 适配方案
我使用的是两个插件
- postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem
- lib-flexible 用于设置 rem 基准值
安装依赖
cnpm install lib-flexible postcss-pxtorem --save-dev
main.js 导入
// 移动端适配
import ‘lib-flexible/flexible’;