-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (58 loc) · 1.68 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 默认参数
let defaultsProp = {
unitToConvert: 'px',
viewportWidth: 1920,
unitPrecision: 5,
viewportUnit: 'vw',
fontViewportUnit: 'vw',
minPixelValue: 1
}
function toFixed(number, precision) {
var multiplier = Math.pow(10, precision + 1),
wholeNumber = Math.floor(number * multiplier)
return (Math.round(wholeNumber / 10) * 10) / multiplier
}
function createPxReplace(viewportSize, minPixelValue, unitPrecision, viewportUnit) {
return function ($0, $1) {
if (!$1) return
var pixels = parseFloat($1)
if (pixels <= minPixelValue) return
return toFixed((pixels / viewportSize) * 100, unitPrecision) + viewportUnit
}
}
const templateReg = /<template>([\s\S]+)<\/template>/gi
const pxGlobalReg = /(\d+)px/gi
// 生成插件的工厂方法
const pluginGenerator = (customOptions = defaultsProp) => {
// 返回插件
return {
// 插件名称
name: 'postcss-px-to-viewport-update',
// transform 钩子
async transform(code, id) {
// eslint-disable-next-line no-unused-vars
let _source = ''
if (/.vue$/.test(id)) {
let _source = ''
if (templateReg.test(code)) {
_source = code.match(templateReg)[0]
}
if (pxGlobalReg.test(_source)) {
let $_source = _source.replace(
pxGlobalReg,
createPxReplace(
customOptions.viewportWidth,
customOptions.minPixelValue,
customOptions.unitPrecision,
customOptions.viewportUnit
)
)
code = code.replace(_source, $_source)
// console.log(code);
}
}
return { code }
}
}
}
export default pluginGenerator