px2vw-mobile
Version:
   # 介绍
61 lines (55 loc) • 1.26 kB
JavaScript
const { getOptions } = require("loader-utils");//获取loader传入参数
const { validate } = require("schema-utils");//参数类型校验
// 参数类型约束
const schema = {
type: "object",
properties: {
width: {
type: "number",
description: "The width of the UI design.",
},
precision: {
type: "number",
description: "Reserved number of decimal places.",
},
minPx: {
type: "number",
description: "Less than how many pixels are not converted.",
},
unit: {
type: "string",
description:"Target units"
},
},
};
// 默认参数
const defaultOptions = {
unit: "vw",
width: 750,
precision: 2,
minPx: 4,
};
module.exports = function loader(source) {
const params = getOptions(this);
// 参数混合
let options = {
...defaultOptions,
...params,
};
// 校验
validate(schema, options, {
name: "px2vw Loader",
baseDataPath: "options",
});
const px2vw = function (px) {
if (px <= options.minPx) {
return px + "px";
} else {
return (
parseFloat((px / options.width) * 100).toFixed(options.precision) +
options.unit
);
}
};
return source.replace(/(\d+)px/g, (_, px) => px2vw(px));
};