Skip to content

Commit 5844953

Browse files
committed
fix: preserve 'use client' directive when injecting utilities
1 parent 998d440 commit 5844953

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

src/index.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,21 @@ export const pluginTailwindCSS = (
178178
path: resourcePath,
179179
});
180180

181-
return `\
182-
import "${pathToFileURL(VIRTUAL_UTILITIES_ID)}?${params.toString()}";
183-
${code}`;
181+
const importStr = `import "${pathToFileURL(VIRTUAL_UTILITIES_ID)}?${params.toString()}";\n`;
182+
183+
const match = code.match(
184+
/^(?:[\s]*|(?:\/\*[\s\S]*?\*\/)|(?:\/\/[^\n]*\n))*(?:(?:"[^"]*"|'[^']*')[ \t]*;?[\s]*)+/,
185+
);
186+
187+
if (match) {
188+
return (
189+
code.slice(0, match[0].length) +
190+
importStr +
191+
code.slice(match[0].length)
192+
);
193+
}
194+
195+
return importStr + code;
184196
},
185197
);
186198

test/rsc-test/index.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import fs from 'node:fs';
2+
import { dirname, resolve } from 'node:path';
3+
import { fileURLToPath } from 'node:url';
4+
import { expect, test } from '@playwright/test';
5+
import { createRsbuild } from '@rsbuild/core';
6+
import { pluginTailwindCSS } from '../../src';
7+
8+
const __dirname = dirname(fileURLToPath(import.meta.url));
9+
10+
test('should preserve "use client" directive at the top of the file', async () => {
11+
const rsbuild = await createRsbuild({
12+
cwd: __dirname,
13+
rsbuildConfig: {
14+
plugins: [pluginTailwindCSS()],
15+
output: {
16+
minify: false,
17+
},
18+
},
19+
});
20+
21+
await rsbuild.build();
22+
23+
const distPath = resolve(__dirname, './dist/static/js');
24+
const files = fs.readdirSync(distPath);
25+
const mainFile = files.find((f) => f.endsWith('.js'));
26+
if (!mainFile) {
27+
throw new Error('No JS file found');
28+
}
29+
const content = fs.readFileSync(resolve(distPath, mainFile), 'utf-8');
30+
31+
// "use client" should be present in the output
32+
expect(content).toMatch(/['"]use client['"]/);
33+
});

0 commit comments

Comments
 (0)