如果需要使用 rem
单位进行适配,推荐使用以下两个工具:
- postcss-pxtorem 是一款 PostCSS 插件,用于将 px 单位转化为 rem 单位
- lib-flexible 用于设置 rem 基准值
安装 $ npm install postcss postcss-pxtorem --save-dev $ npm i -S amfe-flexible
PostCSS 示例配置
下面提供了一份基本的 PostCSS 示例配置,可以在此配置的基础上根据项目需求进行修改。
// postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*'],
},
},
};
其他设计稿尺寸
如果设计稿的尺寸不是 375,而是 750 或其他大小,可以将 rootValue
配置调整为:
// postcss.config.js
module.exports = {
plugins: {
// postcss-pxtorem 插件的版本需要 >= 5.0.0
'postcss-pxtorem': {
rootValue({ file }) {
return file.indexOf('vant') !== -1 ? 37.5 : 75;
},
propList: ['*'],
},
},
};
最后需要在main.js中引入
import 'amfe-flexible' // px转rem