1
1
import { existsSync } from 'node:fs' ;
2
- import { mkdir , mkdtemp , writeFile } from 'node:fs/promises' ;
2
+ import { mkdir , mkdtemp , readFile , writeFile } from 'node:fs/promises' ;
3
+ import { createRequire } from 'node:module' ;
3
4
import { tmpdir } from 'node:os' ;
4
5
import path from 'node:path' ;
5
6
import { pathToFileURL } from 'node:url' ;
@@ -288,11 +289,45 @@ class TailwindRspackPluginImpl {
288
289
289
290
const configPath = path . resolve ( outputDir , 'tailwind.config.mjs' ) ;
290
291
291
- const content = JSON . stringify ( entryModules ) ;
292
-
293
292
await writeFile (
294
293
configPath ,
295
- existsSync ( userConfig )
294
+ await this . #generateTailwindConfig( userConfig , entryModules ) ,
295
+ ) ;
296
+
297
+ return configPath ;
298
+ }
299
+
300
+ async #resolveTailwindCSSVersion( ) : Promise < string > {
301
+ const require = createRequire ( import . meta. url ) ;
302
+ const pkgPath = require . resolve ( 'tailwindcss/package.json' ) ;
303
+
304
+ const content = await readFile ( pkgPath , 'utf-8' ) ;
305
+
306
+ const { version } = JSON . parse ( content ) as { version : string } ;
307
+
308
+ return version ;
309
+ }
310
+
311
+ async #generateTailwindConfig(
312
+ userConfig : string ,
313
+ entryModules : string [ ] ,
314
+ ) : Promise < string > {
315
+ const version = await this . #resolveTailwindCSSVersion( ) ;
316
+
317
+ const { default : satisfies } = await import (
318
+ 'semver/functions/satisfies.js'
319
+ ) ;
320
+
321
+ const content = JSON . stringify ( entryModules ) ;
322
+ if ( satisfies ( version , '^3.3.0' ) ) {
323
+ // Tailwind CSS support using ESM configuration in v3.3.0
324
+ // See:
325
+ // - https://github.com/tailwindlabs/tailwindcss/releases/tag/v3.3.0
326
+ // - https://github.com/tailwindlabs/tailwindcss/pull/10785
327
+ // - https://github.com/rspack-contrib/rsbuild-plugin-tailwindcss/issues/18
328
+ //
329
+ // In this case, we provide an ESM configuration to support both ESM and CJS.
330
+ return existsSync ( userConfig )
296
331
? `\
297
332
import config from '${ pathToFileURL ( userConfig ) } '
298
333
export default {
@@ -302,10 +337,21 @@ export default {
302
337
: `\
303
338
export default {
304
339
content: ${ content }
305
- }` ,
306
- ) ;
340
+ }` ;
341
+ }
307
342
308
- return configPath ;
343
+ // Otherwise, we provide an CJS configuration since TailwindCSS would always use `require`.
344
+ return existsSync ( userConfig )
345
+ ? `\
346
+ const config = require('${ userConfig } ')
347
+ module.exports = {
348
+ ...config,
349
+ content: ${ content }
350
+ }`
351
+ : `\
352
+ module.exports = {
353
+ content: ${ content }
354
+ }` ;
309
355
}
310
356
}
311
357
0 commit comments