diff --git a/src/index.ts b/src/index.ts index 7bbba99..4c07437 100644 --- a/src/index.ts +++ b/src/index.ts @@ -178,9 +178,21 @@ export const pluginTailwindCSS = ( path: resourcePath, }); - return `\ -import "${pathToFileURL(VIRTUAL_UTILITIES_ID)}?${params.toString()}"; -${code}`; + const importStr = `import "${pathToFileURL(VIRTUAL_UTILITIES_ID)}?${params.toString()}";\n`; + + const match = code.match( + /^(?:[\s]*|(?:\/\*[\s\S]*?\*\/)|(?:\/\/[^\n]*(?:\n|$)))*(?:(?:(?:"[^"\n\r]*"|'[^'\n\r]*')[ \t]*;?)(?:[\s]*|(?:\/\*[\s\S]*?\*\/)|(?:\/\/[^\n]*(?:\n|$)))*)+/, + ); + + if (match) { + return ( + code.slice(0, match[0].length) + + importStr + + code.slice(match[0].length) + ); + } + + return importStr + code; }, ); diff --git a/test/rsc-test-react/src/index.js b/test/rsc-test-react/src/index.js new file mode 100644 index 0000000..c1e5e9f --- /dev/null +++ b/test/rsc-test-react/src/index.js @@ -0,0 +1,2 @@ +'use client'; +console.log('hello'); diff --git a/test/rsc-test/index.test.ts b/test/rsc-test/index.test.ts new file mode 100644 index 0000000..db0f139 --- /dev/null +++ b/test/rsc-test/index.test.ts @@ -0,0 +1,33 @@ +import fs from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from '@playwright/test'; +import { createRsbuild } from '@rsbuild/core'; +import { pluginTailwindCSS } from '../../src'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +test('should preserve "use client" directive at the top of the file', async () => { + const rsbuild = await createRsbuild({ + cwd: __dirname, + rsbuildConfig: { + plugins: [pluginTailwindCSS()], + output: { + minify: false, + }, + }, + }); + + await rsbuild.build(); + + const distPath = resolve(__dirname, './dist/static/js'); + const files = fs.readdirSync(distPath); + const mainFile = files.find((f) => f.endsWith('.js')); + if (!mainFile) { + throw new Error('No JS file found'); + } + const content = fs.readFileSync(resolve(distPath, mainFile), 'utf-8'); + + // "use client" should be present in the output + expect(content).toMatch(/['"]use client['"]/); +}); diff --git a/test/rsc-test/src/index.js b/test/rsc-test/src/index.js new file mode 100644 index 0000000..c1e5e9f --- /dev/null +++ b/test/rsc-test/src/index.js @@ -0,0 +1,2 @@ +'use client'; +console.log('hello');