Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement TailwindCSSRspackPlugin #2

Merged
merged 2 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@
"files": ["dist"],
"scripts": {
"build": "rslib build",
"bump": "npx bumpp",
"dev": "rslib build --watch",
"lint": "biome check .",
"lint:write": "biome check . --write",
"prepare": "simple-git-hooks && npm run build",
"test": "playwright test",
"bump": "npx bumpp"
"test": "playwright test"
},
"simple-git-hooks": {
"pre-commit": "npm run lint:write"
},
"dependencies": {
"postcss": "^8.4.47"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@playwright/test": "^1.48.2",
Expand All @@ -35,10 +38,12 @@
"@types/node": "^22.9.0",
"playwright": "^1.48.2",
"simple-git-hooks": "^2.11.1",
"tailwindcss": "^3.4.14",
"typescript": "^5.6.3"
},
"peerDependencies": {
"@rsbuild/core": "1.x"
"@rsbuild/core": "1.x",
"tailwindcss": "^3"
},
"peerDependenciesMeta": {
"@rsbuild/core": {
Expand Down
814 changes: 814 additions & 0 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

222 changes: 222 additions & 0 deletions src/TailwindCSSRspackPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

import type { Rspack } from '@rsbuild/core';

/**
* The options for {@link TailwindRspackPlugin}.
*
* @public
*/
interface TailwindRspackPluginOptions {
/**
* The path to the configuration of Tailwind CSS.
*
* @remarks
*
* The default value is `tailwind.config.js`.
*
* @example
*
* Use absolute path:
*
* ```js
* // rspack.config.js
* import path from 'node:path'
* import { fileURLToPath } from 'node:url'
*
* import { TailwindRspackPlugin } from '@rsbuild/plugin-tailwindcss'
*
* const __dirname = path.dirname(fileURLToPath(import.meta.url))
*
* export default {
* plugins: [
* new TailwindRspackPlugin({
* config: path.resolve(__dirname, './config/tailwind.config.js'),
* }),
* ],
* }
* ```
*
* @example
*
* Use relative path:
*
* ```js
* // rspack.config.js
* import { TailwindRspackPlugin } from '@rsbuild/plugin-tailwindcss'
*
* export default {
* plugins: [
* new TailwindRspackPlugin({
* config: './config/tailwind.config.js',
* }),
* ],
* }
* ```
*/
config?: string;
}

/**
* The Rspack plugin for Tailwind integration.
*
* @public
*/
class TailwindRspackPlugin {
constructor(
private readonly options?: TailwindRspackPluginOptions | undefined,
) {}

/**
* `defaultOptions` is the default options that the {@link TailwindRspackPlugin} uses.
*
* @public
*/
static defaultOptions: Readonly<Required<TailwindRspackPluginOptions>> =
Object.freeze<Required<TailwindRspackPluginOptions>>({
config: 'tailwind.config.js',
});

/**
* The entry point of a Rspack plugin.
* @param compiler - the Rspack compiler
*/
apply(compiler: Rspack.Compiler): void {
new TailwindRspackPluginImpl(
compiler,
Object.assign({}, TailwindRspackPlugin.defaultOptions, this.options),
);
}
}

export { TailwindRspackPlugin };
export type { TailwindRspackPluginOptions };

type NoUndefinedField<T> = {
[P in keyof T]-?: NoUndefinedField<NonNullable<T[P]>>;
};

class TailwindRspackPluginImpl {
name = 'TailwindRspackPlugin';

constructor(
private compiler: Rspack.Compiler,
private options: NoUndefinedField<TailwindRspackPluginOptions>,
) {
const { RawSource } = compiler.webpack.sources;
compiler.hooks.thisCompilation.tap(this.name, (compilation) => {
compilation.hooks.processAssets.tapPromise(this.name, async () => {
await Promise.all(
[...compilation.entrypoints.entries()].map(
async ([entryName, entrypoint]) => {
const cssFiles = entrypoint
.getFiles()
.filter((file) => file.endsWith('.css'))
.map((file) => compilation.getAsset(file))
.filter((file) => !!file);

if (cssFiles.length === 0) {
// Ignore entrypoint without CSS files.
return;
}

// collect all the modules corresponding to specific entry
const entryModules = new Set<string>();

for (const chunk of entrypoint.chunks) {
const modules =
compilation.chunkGraph.getChunkModulesIterable(chunk);
for (const module of modules) {
collectModules(module, entryModules);
}
}

const [
{ default: postcss },
{ default: tailwindcss },
configPath,
] = await Promise.all([
import('postcss'),
import('tailwindcss'),
this.#prepareTailwindConfig(entryName, entryModules),
]);

const postcssTransform = postcss([
// We use a config path to avoid performance issue of TailwindCSS
// See: https://github.com/tailwindlabs/tailwindcss/issues/14229
tailwindcss({
config: configPath,
}),
]);

// iterate all css asset in entry and inject entry modules into tailwind content
await Promise.all(
cssFiles.map(async (asset) => {
const content = asset.source.source();
// transform .css which contains tailwind mixin
// FIXME: add custom postcss config
const transformResult = await postcssTransform.process(
content,
{ from: asset.name },
);
// FIXME: add sourcemap support
compilation.updateAsset(
asset.name,
new RawSource(transformResult.css),
);
}),
);
},
),
);
});
});
}

async #prepareTailwindConfig(
entryName: string,
entryModules: Set<string>,
): Promise<string> {
const userConfig = path.isAbsolute(this.options.config)
? this.options.config
: // biome-ignore lint/style/noNonNullAssertion: should have context
path.resolve(this.compiler.options.context!, this.options.config);

const outputDir = path.resolve(
// biome-ignore lint/style/noNonNullAssertion: should have `output.path`
this.compiler.options.output.path!,
'.rsbuild',
entryName,
);
await mkdir(outputDir, { recursive: true });

const configPath = path.resolve(outputDir, 'tailwind.config.mjs');

await writeFile(
configPath,
`\
import config from '${pathToFileURL(userConfig)}'
export default {
...config,
content: ${JSON.stringify(Array.from(entryModules))}
}`,
);

return configPath;
}
}

function collectModules(
module: Rspack.Module,
entryModules: Set<string>,
): void {
if (module.modules) {
for (const innerModule of module.modules) {
collectModules(innerModule, entryModules);
}
} else if (module.resource) {
entryModules.add(module.resource);
}
}
63 changes: 61 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,54 @@
import type { RsbuildPlugin } from '@rsbuild/core';

import { TailwindRspackPlugin } from './TailwindCSSRspackPlugin.js';

export type PluginTailwindCSSOptions = {
/**
* The path to the configuration of Tailwind CSS.
*
* @remarks
*
* The default value is `tailwind.config.js`.
*
* @example
*
* Use relative path:
*
* ```js
* // rsbuild.config.ts
* import { pluginTailwindCSS } from '@byted-lynx/plugin-tailwindcss'
*
* export default {
* plugins: [
* pluginTailwindCSS({
* config: './config/tailwind.config.js',
* }),
* ],
* }
* ```
*
* @example
*
* Use absolute path:
*
* ```js
* // rsbuild.config.ts
* import path from 'node:path'
* import { fileURLToPath } from 'node:url'
*
* import { pluginTailwindCSS } from '@rsbuild/plugin-tailwindcss'
*
* const __dirname = path.dirname(fileURLToPath(import.meta.url))
*
* export default {
* plugins: [
* pluginTailwindCSS({
* config: path.resolve(__dirname, './config/tailwind.config.js'),
* }),
* ],
* }
* ```
*/
config?: string;
};

Expand All @@ -9,7 +57,18 @@ export const pluginTailwindCSS = (
): RsbuildPlugin => ({
name: 'rsbuild:tailwindcss',

setup() {
console.log('Hello Rsbuild!', options);
setup(api) {
api.modifyBundlerChain({
order: 'post',
handler(chain) {
chain
.plugin('tailwindcss')
.use(TailwindRspackPlugin, [
{ config: options.config ?? 'tailwind.config.js' },
]);
},
});
},
});

export { TailwindRspackPlugin } from './TailwindCSSRspackPlugin.js';
Loading