|
1 | 1 | import { defineAddon, defineAddonOptions } from '../../core/index.ts'; |
2 | 2 | import { imports, vite } from '../../core/tooling/js/index.ts'; |
3 | 3 | import * as svelte from '../../core/tooling/svelte/index.ts'; |
| 4 | +import * as css from '../../core/tooling/css/index.ts'; |
4 | 5 | import { parseCss, parseJson, parseScript, parseSvelte } from '../../core/tooling/parsers.ts'; |
5 | 6 |
|
6 | 7 | const plugins = [ |
@@ -59,38 +60,28 @@ export default defineAddon({ |
59 | 60 | }); |
60 | 61 |
|
61 | 62 | sv.file(files.stylesheet, (content) => { |
62 | | - let atRules = parseCss(content).ast.nodes.filter((node) => node.type === 'atrule'); |
63 | | - |
64 | | - const findAtRule = (name: string, params: string) => |
65 | | - atRules.find( |
66 | | - (rule) => |
67 | | - rule.name === name && |
68 | | - // checks for both double and single quote variants |
69 | | - rule.params.replace(/['"]/g, '') === params |
70 | | - ); |
71 | | - |
72 | | - let code = content; |
73 | | - const importsTailwind = findAtRule('import', 'tailwindcss'); |
74 | | - if (!importsTailwind) { |
75 | | - code = "@import 'tailwindcss';\n" + code; |
76 | | - // reparse to account for the newly added tailwindcss import |
77 | | - atRules = parseCss(code).ast.nodes.filter((node) => node.type === 'atrule'); |
78 | | - } |
| 63 | + const { ast, generateCode } = parseCss(content); |
79 | 64 |
|
80 | | - const lastAtRule = atRules.findLast((rule) => ['plugin', 'import'].includes(rule.name)); |
81 | | - const pluginPos = lastAtRule!.source!.end!.offset; |
| 65 | + // since we are prepending all the `AtRule` let's add them in reverse order, |
| 66 | + // so they appear in the expected order in the final file |
82 | 67 |
|
83 | 68 | for (const plugin of plugins) { |
84 | 69 | if (!options.plugins.includes(plugin.id)) continue; |
85 | 70 |
|
86 | | - const pluginRule = findAtRule('plugin', plugin.package); |
87 | | - if (!pluginRule) { |
88 | | - const pluginImport = `\n@plugin '${plugin.package}';`; |
89 | | - code = code.substring(0, pluginPos) + pluginImport + code.substring(pluginPos); |
90 | | - } |
| 71 | + css.addAtRule(ast, { |
| 72 | + name: 'plugin', |
| 73 | + params: `'${plugin.package}'`, |
| 74 | + append: false |
| 75 | + }); |
91 | 76 | } |
92 | 77 |
|
93 | | - return code; |
| 78 | + css.addAtRule(ast, { |
| 79 | + name: 'import', |
| 80 | + params: `'tailwindcss'`, |
| 81 | + append: false |
| 82 | + }); |
| 83 | + |
| 84 | + return generateCode(); |
94 | 85 | }); |
95 | 86 |
|
96 | 87 | if (!kit) { |
|
0 commit comments