|
| 1 | +import fs from 'fs'; |
| 2 | +import less from 'less'; |
| 3 | +import MagicString from 'magic-string'; |
| 4 | + |
| 5 | +const lessToCss = async (id: string, lessOptions: Less.Options): Promise<string> => { |
| 6 | + const source = fs.readFileSync(id, 'utf-8'); |
| 7 | + const output = await (less as any).render(source, { |
| 8 | + ...lessOptions, |
| 9 | + filename: id, |
| 10 | + }); |
| 11 | + return (output as Less.RenderOutput).css || ''; |
| 12 | +}; |
| 13 | + |
| 14 | +export default function lessCompilerPlugin( |
| 15 | + options: { |
| 16 | + include?: RegExp; |
| 17 | + exclude?: RegExp; |
| 18 | + lessOptions?: Less.Options; |
| 19 | + } = {}, |
| 20 | +) { |
| 21 | + const { include = /tdesign-web-components.*\.js/, exclude, lessOptions = {} } = options; |
| 22 | + |
| 23 | + return { |
| 24 | + name: 'vite-plugin-less-compiler', |
| 25 | + async transform(code, id) { |
| 26 | + if (exclude && exclude.test(id)) { |
| 27 | + return null; |
| 28 | + } |
| 29 | + |
| 30 | + if (!include.test(id)) { |
| 31 | + return null; |
| 32 | + } |
| 33 | + |
| 34 | + const magicString = new MagicString(code); |
| 35 | + const ast = this.parse(code); |
| 36 | + |
| 37 | + for (const node of ast.body) { |
| 38 | + const { type = '', source = {}, specifiers } = node; |
| 39 | + if (type !== 'ImportDeclaration' || !source.value.match(/^.*\.less$/)) { |
| 40 | + continue; |
| 41 | + } |
| 42 | + if (!specifiers && specifiers?.[0]?.type !== 'ImportDefaultSpecifier') { |
| 43 | + continue; |
| 44 | + } |
| 45 | + const [{ local = {} }] = specifiers; |
| 46 | + // 这里只能使用 for loop |
| 47 | + // eslint-disable-next-line no-await-in-loop |
| 48 | + const css = await lessToCss(source.value, lessOptions); |
| 49 | + magicString.overwrite(node.start, node.end, `const ${local.name} = \`${css}\``); |
| 50 | + } |
| 51 | + return { |
| 52 | + code: magicString.toString(), |
| 53 | + }; |
| 54 | + }, |
| 55 | + }; |
| 56 | +} |
0 commit comments