px转rem适配方案之postcss-pxtorem

发布时间 2023-08-29 10:32:50作者: 小羽羽

一、安装

npm install postcss-pxtorem --save-dev

二、增加postcss.config.js文件

在目录文件下增加postcss.config.js并添加相关配置

// https://github.com/michael-ciniawsky/postcss-load-config

module.exports = {
  'plugins': {
    // to edit target browsers: use "browserslist" field in package.json
    'autoprefixer': {},
    'postcss-pxtorem': {
      rootValue: 16, // rem 相对于 px 转换的基准值
      propList: ['*'], // 需要转换的 CSS 属性,* 表示全部
      unitPrecision: 5, // 转换后的小数位数
      exclude: (e) => { // 只对src/views/largeScreen文件进行px转rem,其他文件不转换
        if(/src(\\|\/)views(\\|\/)largeScreen/.test(e)) {
          return false
        } else {
          return true
        }
      }
    }
  }
}

// npm相关配置介绍 `https://www.npmjs.com/package/postcss-pxtorem`

1.`rootValue`(数字 | 函数):表示根元素的字体大小,或者根据输入参数返回根元素的字体大小。

2.`unitPrecision`(数字):允许 REM 单位增长的小数位数。

3.`propList`(数组):可以从像素(px)转换为 REM 的属性列表。值必须完全匹配。
使用通配符 * 以启用所有属性。例如:['*']
在单词的开头或结尾使用 *。(['*position*'] 将匹配 background-position-y)
使用 ! 来排除某个属性。例如:['*', '!letter-spacing']
可以将 "not" 前缀与其他前缀结合使用。例如:['*', '!font*']

4.`selectorBlackList`(数组):要忽略并保留为像素(px)的选择器。
如果值是字符串,它会检查选择器是否包含该字符串。
['body'] 将匹配 .body-class
如果值是正则表达式,它会检查选择器是否与正则表达式匹配。
[/^body$/] 将匹配 body,但不匹配 .body

5.`replace`(布尔值):替换包含 rem 的规则而不是添加回退。

6.`mediaQuery`(布尔值):允许在媒体查询中转换像素(px)。

7.`minPixelValue`(数字):设置要替换的最小像素值。

8.`exclude`(字符串、正则表达式、函数):要忽略并保留为像素(px)的文件路径。
如果值是字符串,它会检查文件路径是否包含该字符串。
'exclude' 将匹配 \project\postcss-pxtorem\exclude\path
如果值是正则表达式,它会检查文件路径是否与正则表达式匹配。
/exclude/i 将匹配 \project\postcss-pxtorem\exclude\path
如果值是函数,您可以使用排除函数返回 true,并将忽略该文件。
回调函数将文件路径作为参数传递,应返回一个布尔结果。
function (file) { return file.indexOf('exclude') !== -1; }

三、vue.config.js中配置

module.exports = {
    //....
    
    css: {
    loaderOptions: {
      postcss: {
        config: {
          path: './postcss.config.js'
          }
      	}
      }
  	},
    
    //....
}

四、增加适配js、配置在main.js中

rem.js

//rem等比适配配置文件

//基准大小
const baseSize = 16

//设置 rem 函数
function setRem() {
  //当前页面宽度相对于1920宽的缩放比例, 可根据自己需要修改
  const scale = document.documentElement.clientWidth / 1920
  //设置页面根节点字体大小, 字体大小最小为12
  let fontSize = baseSize * Math.min(scale, 2) > 12 ? baseSize * Math.min(scale, 2) : 12
  document.documentElement.style.fontSize = fontSize + 'px'
}

//初始化
setRem()
//改变窗口大小重新设置rem
window.onresize = function () {
  setRem()
}

main.js

import './utils/rem'  // 我文件放在utils下,引入即可

五、总结

以上是 postcss-pxtorem 插件的一些配置选项的说明。针对某页面固定使用,通过exclude字段配置。