Vuecli4最新移动端(px转rem)适配方法
首先安装脚手架
1.先确认是否有安装过vue-cli,输入vue -V(大写)
//如有的话,就用下面命令卸载;
2. 输入命令
cnpm install -g @vue/cli
指定版本:
如果是3.0以下
npm install -g vue-cli@版本号
如果是3.0以上
npm install -g @vue/cli@版本号
创建和初始化项目
vue create (你的项目名)
回车键确认执行,空格键进行选择所需要的配置
选择自定义配置
manually select features
接下来这步很重要,配置文件要选择存放到独立文件
In dedicated config file
安装适配插件
1.首先输入命令
npm i amfe-flexible -S
2.在main.js中引入模块
import ‘amfe-flexible’
amfe-flexible 用于设置 rem 基准值
使用 amfe-flexible 动态设置 rem 基准值(html 标签的字体大小)
或者可以自己创建一个rem.js文件放在assets里然后将其在main.js里导入也是可以的。
const baseSize = 40;
function setRem() {
const scale = document.documentElement.clientWidth / 750;
document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
setRem();
window.onresize = function () {
setRem()
};
3.安装postcss-pxtorem插件 (是将px转为rem)。
npm install postcss-pxtorem -D
然后在项目根目录创建postcss.config.js文件
(这就是为什么刚才要初始化项目的时候必须要配置 存放到独立文件 如果选择放在package.json里面就无效了)
Module.exports = {
Plugins: {
“postcss-pxtorem”: {
// 设计稿 375: 37.5
// 设计稿 750: 75
// Vant 是基于375
rootValue: 37.5,
propList: [“*”]
}
}
}
最后切记重新启动启动服务npm run serve,不然配置文件不生效
如果安装完postcss报错?“ Error: PostCSS plugin postcss-pxtorem requires PostCSS 8.”
安装指定postcss-pxtorem版本为5.1.1,就不会报这个错了。
指定安装版本快捷方式:
直接在package.json里将postcss-pxtorem改为5.1.1,然后输入命令npm i
重新安装npm,就能自动安装指定版本啦!
安装后,package.json里面可以看到postcss-pxtorem版本已经变成指定的了。