xccjk / x-blog

学习笔记
17 stars 2 forks source link

postcss #94

Open xccjk opened 1 year ago

xccjk commented 1 year ago

postcss-pxtorem

postcss-pxtorem是用来自动将px单位转为rem单位,来实现不同端间的自适应的

安装依赖:

pnpm install postcss postcss-pxtorem -D

几种常见的使用方式

webpack中配置

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(css|less)$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  require('postcss-pxtorem')({
                    rootValue: 75,
                    propList: ['*']
                  })
                ]
              }
            }
          }
        ]
      }
    ]
  }
}

postcss.config.js中配置

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 75, // 这个值是设计稿宽度的 1/10,如果你的设计稿宽度为750px,则rootValue应该设置为75
      propList: ['*'],
      unitPrecision: 5,
    }
  }
}

可能遇到的问题

只想对指定的文件进行编译

通过exclude属性来控制对指定文件进行编译

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 75, // 这个值是设计稿宽度的 1/10,如果你的设计稿宽度为750px,则rootValue应该设置为75
      propList: ['*'],
      unitPrecision: 5,
      exclude: (file)=>{  // 只对src/styles下的样式文件进行编译
        if (file.indexOf('src/styles') !== -1) return false;
        return true;
      }
    }
  }
}

有的样式不想进行px转rem

通过Px替换px,来避免rem的转换

border: 1Px solid #ccc
xccjk commented 1 year ago

设置根节点字体大小

// 设置 rem 函数
function setRem() {
  // 设置页面根节点字体大小, 字体大小最小为12
  document.documentElement.style.fontSize = (document.documentElement.clientWidth * 100) / 375 + 'px';
}
//初始化
setRem();
//改变窗口大小时重新设置 rem,这里最好加上节流
window.onresize = function () {
  setRem();
}