Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

postcss #94

Open
xccjk opened this issue Jun 13, 2023 · 1 comment
Open

postcss #94

xccjk opened this issue Jun 13, 2023 · 1 comment

Comments

@xccjk
Copy link
Owner

xccjk commented Jun 13, 2023

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
Copy link
Owner Author

xccjk commented Jun 13, 2023

设置根节点字体大小

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant