Skip to content

Commit

Permalink
improve robustness
Browse files Browse the repository at this point in the history
  • Loading branch information
AdrianGonz97 committed Feb 27, 2025
1 parent 0c0cd3b commit 6db0590
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions packages/addons/tailwindcss/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,29 +73,33 @@ export default defineAddon({
});

sv.file('src/app.css', (content) => {
let code = content;
let atRules = parseCss(content).ast.nodes.filter((node) => node.type === 'atrule');

const findAtRule = (name: string, params: string) =>
atRules.find(
(rule) =>
rule.name === name &&
// checks for both double and single quote variants
rule.params.replace(/['"]/g, '') === params
);

const importsTailwind = content.match(/@import ["']tailwindcss["']/);
let code = content;
const importsTailwind = findAtRule('import', 'tailwindcss');
if (!importsTailwind) {
code = "@import 'tailwindcss';\n" + code;
}

const lastAtRule = code.match(/@(import|plugin).*[;]/gm)?.at(-1);
if (!lastAtRule) throw new Error('Impossible condition: Missing `@import` atrule.');
const pluginPos = code.indexOf(lastAtRule) + lastAtRule.length;
// reparse to account for the newly added tailwindcss import
atRules = parseCss(code).ast.nodes.filter((node) => node.type === 'atrule');

const lastAtRule = atRules.findLast((rule) => ['plugin', 'import'].includes(rule.name));
const pluginPos = lastAtRule!.source!.end!.offset;

const { ast } = parseCss(code);
const atRules = ast.nodes.filter((x) => x.type === 'atrule');
for (const plugin of plugins) {
if (!options.plugins.includes(plugin.id)) continue;

const atRule = atRules.find(
(rule) =>
rule.name === 'plugin' &&
// Checks for both double and single quote variants
rule.params.replace(/['"]/g, '') === plugin.package
);
if (!atRule) {
const pluginRule = findAtRule('plugin', plugin.package);
if (!pluginRule) {
const pluginImport = `\n@plugin '${plugin.package}';`;
code = code.substring(0, pluginPos) + pluginImport + code.substring(pluginPos);
}
Expand Down

0 comments on commit 6db0590

Please sign in to comment.