Shaoli's Blog

自定义webpack配置,将react / vue 中内联样式的 px 转 rem

1、新建jsxPx2RemLoader.js,要先安装 loader-utils

const loaderUtils = require("loader-utils")


// 默认参数
const defaultopts = {
  rootValue100,  // px 和 rem 的转换比例
  unitPrecision: 2  // 保留精度,也就是小数位数
}


module.exports = function (source{
  // 获取webpack配置好的参数
  const opts = loaderUtils.getOptions(this)
  // 将参数组合
  const config = Object.assign({}, defaultopts, opts)
  const ZPXRegExp = /\b(\d+(\.\d+)?)px\b/
  let pxGlobalRegExp = new RegExp(ZPXRegExp.source, "g")
  if (this.cacheable) {
    this.cacheable()
  }
  // 先test下有没有符合的如果有再进行替换
  if (pxGlobalRegExp.test(source)) {
    return source.replace(pxGlobalRegExp, ($0, $1) => {
      let val = $1 / config.rootValue
      // 精确到几位
      val = parseFloat(val.toFixed(config.unitPrecision))
      return val === 0 ? val : val + "rem"
    })
  } else {
    return source
  }
}


2、然后自定义webpack配置

webpack: (config, options) => {
 // 实现行内样式 px2rem
 config.module.rules.push({
 test: /\.(tsx|jsx)$/,
 loaders: {
   loader: './public/js/jsxPx2RemLoader',
   options: {
     rootValue: 75,
     unitPrecision: 5
   }
  }
 })
 return config
}


接下来见证效果

<div style={{ fontSize: '60px' }}>12222</div>
# 被转换为
<div style="font-size: 0.8rem;">12222</div>


    评论列表

  • 暂无评论...快来说说吧!
person
0 / 16
comment
0 / 100