一.vw 方案(推荐)
1.安装依赖
npm i -D postcss-px2vp
2.然后在项目根目录创建 postcss.config.js 文件:
module.exports = {
plugins: {
'postcss-px2vp': {
viewportWidth(rule) { // 1. 如果设计稿宽度是750px + 使用Vant
const file = rule.source?.input.file
return file?.includes('vant') ? 375 : 750;
},
// viewportWidth: 750, // 2.如果设计稿宽度是 750px + 不适用Vant
// viewportWidth: 375, // 3.如果设计稿宽度是 375px + 无论是否使用Vant
propList: ['*','!font*','!line-height','!letter-spacing'],
},
},
};
这个文件会被自执行
说明:
使用 postcss-px2vp,而不是 postcss-px-to-viewport,是因为后者:
不支持设置动态 viewportWidth ,就无法同时支持宽度是 750px 的设计搞 + Vant
不支持 PostCSS 8
Vant 的设计稿宽度是 375px,但我们的设计稿宽度大多是 750px
字体不转换,保持 px 单位
二、rem 方案
yarn add amfe-flexible
或者使用
npm i amfe-flexible
然后在项目根目录中创建 postcss.config.js 文件:
module.exports = {
plugins: {
// postcss-pxtorem 插件的版本需要 >= 5.0.0
// 适用版本 5.1.1
// yarn add -D postcss-pxtorem@5.1.1
// npm install postcss-pxtorem@5.1.1 -D
'postcss-pxtorem': {
rootValue({ file }) { // 如果设计稿宽度是 750px + Vant
// 判断是否是vant的文件 如果是就使用 37.5为根节点字体大小
// 否则使用75 因为vant使用的设计标准为375 但是市场现在的主流设置尺寸是750
return file.indexOf('vant') !== -1 ? 37.5 : 75;
},
// rootValue: 75, // 2.如果设计稿宽度是 750px + 不适用Vant
// rootValue: 37.5, // 3.如果设计稿宽度是 375px + 无论是否使用Vant
// 配置哪些文件中的尺寸需要转化为rem *表示所有的都要转化
propList: ['*','!font*','!line-height','!letter-spacing'],
},
},
};
这个文件会被自执行
说明:
1. amfe-flexible 设置 rem 的基准值(即<html style="font-size: XXXpx">)
2. postcss-pxtorem 是一个 PostCSS 插件,将 px 转为 rem