仓库地址: github.com/gitgundam/u…
npm地址:www.npmjs.com/package/uno…
使用方式:
npm i -D unocss-preset-rem-to-vw
效果:
without
.m-2 {
margin: 0.5rem;
}
.m-8px {
margin: 8px;
}
with
.m-2 {
margin: 2.1333vw;
}
.m-8px {
margin: 2.1333vw;
}
实现方式:
import type { Preset } from 'unocss'
const remRE = /(-?[\.\d]+)rem/g
const pxRE = /(-?[\.\d]+)px/g
export interface PxToVwOptions {
baseFontSize?: number
baseWidth?: number
unitPrecision?: number
}
export default function remToVwPreset(options: PxToVwOptions = {}): Preset {
const { baseFontSize = 16, baseWidth = 375, unitPrecision = 4 } = options
const pxToVw = (px: number) => ((100 / baseWidth) * px).toFixed(unitPrecision)
return {
name: 'preset-rem-to-vw',
postprocess: (util) => {
util.entries.forEach((i) => {
const value = i[1]
if (value && typeof value === 'string')
if (remRE.test(value))
i[1] = value.replace(
remRE,
(_, p1) => `${pxToVw(p1 * baseFontSize)}vw`
)
else if (pxRE.test(value))
i[1] = value.replace(pxRE, (_, p1) => `${pxToVw(p1)}vw`)
})
},
}
}