const loaderUtils = require("loader-utils")
// 默认参数
const defaultopts = {
rootValue: 100, // 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>
©2018-2020 hongshali.com 版权所有 ICP证:闽ICP备18029655号-1