基于 vue-cli4.0 + webpack 4 + vant ui + sass+ rem 适配方案+axios 封装,构建手机端模板脚手架
Vue CLI
需要 Node.js 8.9 或更高版本 (推荐 8.11.0+)。你可以使用 nvm 或
nvm-windows 在同一台电脑中管理多个 Node 版本。
本示例 Node.js 12.14.1
npm install
npm run serve
目录
- √ Vue-cli4
- √ 配置多环境变量
- √ rem 适配方案
- √ VantUI 组件按需加载
- √ Sass 全局样式
- √ Vuex 状态管理
- √ Vue-router
- √ Axios 封装及接口管理
- √ Webpack 4 vue.config.js 基础配置
- √ 配置 alias 别名
- √ 配置 proxy 跨域
- √ 配置 打包分析
- √ 配置 externals 引入 cdn 资源
- √ 去掉 console.log
- √ splitChunks 单独打包第三方模块
- √ 添加 IE 兼容
- √ Eslint+Pettier 统一开发规范
package.json
里的 scripts
配置 serve
stage
build
,通过 --mode xxx
来执行不同环境
- 通过
npm run serve
启动本地 , 执行development
- 通过
npm run stage
打包测试 , 执行staging
- 通过
npm run build
打包正式 , 执行production
"scripts": {
"serve": "vue-cli-service serve --open",
"stage": "vue-cli-service build --mode staging",
"build": "vue-cli-service build",
}
以 VUE_APP_
开头的变量,在代码中可以通过 process.env.VUE_APP_
访问。
比如,VUE_APP_ENV = 'development'
通过process.env.VUE_APP_ENV
访问。
除了 VUE_APP_*
变量之外,在你的应用代码中始终可用的还有两个特殊的变量NODE_ENV
和BASE_URL
在项目根目录中新建.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'
这里我们并没有定义很多变量,只定义了基础的 VUE_APP_ENV development
staging
production
变量我们统一在 src/config/env.*.js
里进行管理。
config/index.js
// 根据环境引入不同配置 process.env.NODE_ENV
const config = require('./env.' + process.env.VUE_APP_ENV)
module.exports = config
配置对应环境的变量,拿本地环境文件 env.development.js
举例,用户可以根据需求修改
// 本地环境配置
module.exports = {
title: 'vue-h5-template',
baseUrl: 'http://localhost:9018', // 项目地址
baseApi: 'https://test.xxx.com/api', // 本地api请求地址
APPID: 'xxx',
APPSECRET: 'xxx'
}
根据环境不同,变量就会不同了
// 根据环境不同引入不同baseApi地址
import {baseApi} from '@/config'
console.log(baseApi)
Vant 中的样式默认使用px
作为单位,如果需要使用rem
单位,推荐使用以下两个工具:
- postcss-pxtorem 是一款
postcss
插件,用于将单位转化为rem
- lib-flexible 用于设置
rem
基准值
下面提供了一份基本的 postcss
配置,可以在此配置的基础上根据项目需求进行修改
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
plugins: {
autoprefixer: {
overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8']
},
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*']
}
}
}
更多详细信息: vant