import {forEach, map} from "lodash"; //c 为class 例如 class="wi-10" //w 为样式style 例如 width:10rpx //t 为值开头 例如 color:#000 //w 为值结尾 例如 width:10rpx export default function AutoStylePlugin(k: { c: string, s: string, t: string, w: string }[]) { return { name: 'AutoStyle-plugin', transform(code: string, id: string) { if (!/node_modules/.test(id) && k.length > 0) { if (id.endsWith('.vue') || id.endsWith('.nvue')) { const a = "(?:" + map(k, (v, i) => '\\b' + v.c + '-' + (k.length - 1 == i ? '' : '|')).join('') + ")[a-zA-Z0-9]+" const rege = new RegExp(a, 'g') const classWiRegex: RegExp = new RegExp('class="[^"]*' + a, 'g') if (classWiRegex.test(code)) { const classList = Array.from(new Set(code.match(classWiRegex)?.join(',').match(rege) || [])) let style = '' for (const classListKey in classList) { const splitSplit = classList[classListKey].split('-') forEach(k, v => { if (v.c === splitSplit[0]) { style += `.${classList[classListKey]}{${v.s}:${v.t ? v.t : ''}${splitSplit[1]}${v.w ? v.w : ''};}\n` } }) } code += `` } } } return { code, map: null }; } }; }