umi3.x配置px2rem
1.引入 “postcss-pxtorem”: “5.1.1”
yarn add postcss-pxtorem@5.1.1 --dev
指定版本可以避免找不到的问题
2.在config.js/umirc.js文件中,添加extraPostCSSPlugins配置
extraPostCSSPlugins: [
pxtorem({
rootValue: 100, //这里根据设计稿大小配置,一般是375
propList: ['*'],
selectorBlackList: ['.am-'], // 过滤掉.am-开头的class,不进行rem转换
}),
],
3.在根文件渲染initRem方法,重置当前页面的根元素的font-size大小
这里以750px设计稿为最大值,320px为最小值设置font-size为100,就可以直接照着750px设计稿的大小写样式的px大小了
export function initRem(): void {
const docEle = document.documentElement;
function setHtmlFontSize() {
let deviceWidth = docEle.clientWidth || window.innerWidth;
if (deviceWidth >= 750) {
deviceWidth = 750;
}
if (deviceWidth <= 320) {
deviceWidth = 320;
}
const fontSize = deviceWidth / 7.5;
docEle.style.fontSize = fontSize.toFixed(3) + 'px';
}
setHtmlFontSize();
window.addEventListener('resize', setHtmlFontSize);
}
4.结果 输入px的样式自动转化成rem,不支持行内样式的自动转化