10天掌握webpack 5.0 pxtorem

主要是使用 px2rem-loader 插件配合lib-flexible来实现

 

ib-flexible 可以自己手写 

 

  let docEle = document.documentElement;
  function setRemUnit () {
    //750/10=75 375/10=37.5
    docEle.style.fontSize = docEle.clientWidth / 10 + 'px';
  }
  setRemUnit();
  window.addEventListener('resize', setRemUnit);

安装   px2rem-loader 插件

cnpm i px2rem-loader  -D

在  webpack.config.js 中 配置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
 mode: 'development',
  devtool:false,
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    publicPath: "/assets"
  },
  module: {
    rules: [
      { test: /\.css$/, use: ['style-loader','css-loader', 'postcss-loader',
          {
            loader: 'px2rem-loader',
            options: {
              remUnit: 75,
              remPrecision: 8
            }
          }
      ]},
      { test: /\.less$/, use: ['style-loader','css-loader', 'postcss-loader', 'less-loader'] }
    ]
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    compress: true,
    port: 8080,
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({ template: './src/index.html' }),
  ]
};

使用例子:

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webpack5</title>
</head>
<body>
<!-- <div>webpack</div>-->
<!-- <div id="less-container">less-container</div>-->
 <div class="page">pxtorem</div>
<!-- <input placeholder="请输入"/>-->
</body>

</html>
<script>
  let docEle = document.documentElement;
  function setRemUnit () {
    //750/10=75 375/10=37.5
    docEle.style.fontSize = docEle.clientWidth / 10 + 'px';
  }
  setRemUnit();
  window.addEventListener('resize', setRemUnit);
</script>

css  

.page {
    width: 750px;
    height: 40px;
    background-color: yellow;
    font-size: 16px;
}

效果显示:

 

 

 

 

 

这里 页面的标准是 750px  750 /75 = 10 rem  

设置font-size:  75px

docEle.style.fontSize = docEle.clientWidth / 10 + 'px';

根据传入的字体px  去转换:

16/75 = 0.21333333333rem

posted @ 2021-02-05 17:12  1点  阅读(220)  评论(0编辑  收藏  举报