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: support custom postcss options #9

Merged
merged 1 commit into from
Nov 12, 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
56 changes: 37 additions & 19 deletions src/TailwindCSSRspackPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

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

/**
* The options for {@link TailwindRspackPlugin}.
Expand All @@ -15,10 +15,6 @@ interface TailwindRspackPluginOptions {
/**
* The path to the configuration of Tailwind CSS.
*
* @remarks
*
* The default value is `tailwind.config.js`.
*
* @example
*
* Use absolute path:
Expand Down Expand Up @@ -58,7 +54,36 @@ interface TailwindRspackPluginOptions {
* }
* ```
*/
config?: string;
config: string;

/**
* The postcss options to be applied.
*
* @example
*
* Use `cssnano`:
*
* ```js
* // rspack.config.js
* import { TailwindRspackPlugin } from '@rsbuild/plugin-tailwindcss'
*
* export default {
* plugins: [
* new TailwindRspackPlugin({
* postcssOptions: {
* plugins: {
* cssnano: process.env['NODE_ENV'] === 'production' ? {} : false,
* },
* },
* }),
* ],
* }
* ```
*/
postcssOptions: Exclude<
PostCSSLoaderOptions['postcssOptions'],
(loaderContext: Rspack.LoaderContext) => void
>;
}

/**
Expand All @@ -67,9 +92,7 @@ interface TailwindRspackPluginOptions {
* @public
*/
class TailwindRspackPlugin {
constructor(
private readonly options?: TailwindRspackPluginOptions | undefined,
) {}
constructor(private readonly options: TailwindRspackPluginOptions) {}

/**
* `defaultOptions` is the default options that the {@link TailwindRspackPlugin} uses.
Expand All @@ -79,33 +102,27 @@ class TailwindRspackPlugin {
static defaultOptions: Readonly<Required<TailwindRspackPluginOptions>> =
Object.freeze<Required<TailwindRspackPluginOptions>>({
config: 'tailwind.config.js',
postcssOptions: {},
});

/**
* 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),
);
new TailwindRspackPluginImpl(compiler, 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>,
private options: TailwindRspackPluginOptions,
) {
const { RawSource } = compiler.webpack.sources;
compiler.hooks.thisCompilation.tap(this.name, (compilation) => {
Expand Down Expand Up @@ -146,6 +163,7 @@ class TailwindRspackPluginImpl {
]);

const postcssTransform = postcss([
...(options.postcssOptions?.plugins ?? []),
// We use a config path to avoid performance issue of TailwindCSS
// See: https://github.com/tailwindlabs/tailwindcss/issues/14229
tailwindcss({
Expand All @@ -161,7 +179,7 @@ class TailwindRspackPluginImpl {
// FIXME: add custom postcss config
const transformResult = await postcssTransform.process(
content,
{ from: asset.name },
{ from: asset.name, ...options.postcssOptions },
);
// FIXME: add sourcemap support
compilation.updateAsset(
Expand Down
40 changes: 38 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { RsbuildPlugin } from '@rsbuild/core';
import type {
PostCSSLoaderOptions,
RsbuildPlugin,
Rspack,
} from '@rsbuild/core';

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

Expand Down Expand Up @@ -58,13 +62,45 @@ export const pluginTailwindCSS = (
name: 'rsbuild:tailwindcss',

setup(api) {
let postcssOptions: Exclude<
PostCSSLoaderOptions['postcssOptions'],
(loaderContext: Rspack.LoaderContext) => void
>;

api.modifyRsbuildConfig({
order: 'post',
handler(config, { mergeRsbuildConfig }) {
return mergeRsbuildConfig(config, {
tools: {
postcss(config) {
if (typeof config.postcssOptions === 'function') {
throw new Error(
'pluginTailwindCSS does not support using `tools.postcss` as function',
);
}
if (config.postcssOptions) {
// Remove `tailwindcss` from `postcssOptions`
// to avoid `@tailwind` being transformed by `postcss-loader`.
config.postcssOptions.plugins =
config.postcssOptions.plugins?.filter(
(p) =>
'postcssPlugin' in p && p.postcssPlugin !== 'tailwindcss',
) ?? [];
postcssOptions = config.postcssOptions;
}
},
},
});
},
});

api.modifyBundlerChain({
order: 'post',
handler(chain) {
chain
.plugin('tailwindcss')
.use(TailwindRspackPlugin, [
{ config: options.config ?? 'tailwind.config.js' },
{ config: options.config ?? 'tailwind.config.js', postcssOptions },
]);
},
});
Expand Down
15 changes: 15 additions & 0 deletions test/postcss-config/flex-to-grid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @returns {import('postcss').AcceptedPlugin}
*/
export default function () {
return {
postcssPlugin: 'flex-to-grid',
Declaration: {
display(decl) {
if (decl.value === 'flex') {
decl.value = 'grid';
}
},
},
};
}
35 changes: 35 additions & 0 deletions test/postcss-config/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { dirname } 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 build with postcss.config.js', async ({ page }) => {
const rsbuild = await createRsbuild({
cwd: __dirname,
rsbuildConfig: {
plugins: [pluginTailwindCSS()],
},
});

await rsbuild.build();
const { server, urls } = await rsbuild.preview();

await page.goto(urls[0]);

const display = await page.evaluate(() => {
const el = document.getElementById('test');

if (!el) {
throw new Error('#test not found');
}

return window.getComputedStyle(el).getPropertyValue('display');
});

expect(display).toBe('grid');

await server.close();
});
6 changes: 6 additions & 0 deletions test/postcss-config/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import tailwindcss from 'tailwindcss';
import flexToGrid from './flex-to-grid';

export default {
plugins: [tailwindcss(), flexToGrid()],
};
11 changes: 11 additions & 0 deletions test/postcss-config/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import 'tailwindcss/utilities.css';

function className() {
return 'flex';
}

const root = document.getElementById('root');
const element = document.createElement('div');
element.id = 'test';
element.className = className();
root.appendChild(element);
15 changes: 15 additions & 0 deletions test/tools-postcss/flex-to-grid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @returns {import('postcss').AcceptedPlugin}
*/
export default function () {
return {
postcssPlugin: 'flex-to-grid',
Declaration: {
display(decl) {
if (decl.value === 'flex') {
decl.value = 'grid';
}
},
},
};
}
80 changes: 80 additions & 0 deletions test/tools-postcss/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { dirname } 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 build with tools.postcss with tailwindcss', async ({ page }) => {
const { default: tailwindcss } = await import('tailwindcss');
const rsbuild = await createRsbuild({
cwd: __dirname,
rsbuildConfig: {
plugins: [pluginTailwindCSS()],
tools: {
postcss: {
postcssOptions: {
plugins: [tailwindcss()],
},
},
},
},
});

await rsbuild.build();
const { server, urls } = await rsbuild.preview();

await page.goto(urls[0]);

const display = await page.evaluate(() => {
const el = document.getElementById('test');

if (!el) {
throw new Error('#test not found');
}

return window.getComputedStyle(el).getPropertyValue('display');
});

expect(display).toBe('flex');

await server.close();
});

test('should build with tools.postcss with custom plugin', async ({ page }) => {
const { default: tailwindcss } = await import('tailwindcss');
const { default: flexToGrid } = await import('./flex-to-grid.js');
const rsbuild = await createRsbuild({
cwd: __dirname,
rsbuildConfig: {
plugins: [pluginTailwindCSS()],
tools: {
postcss: {
postcssOptions: {
plugins: [flexToGrid()],
},
},
},
},
});

await rsbuild.build();
const { server, urls } = await rsbuild.preview();

await page.goto(urls[0]);

const display = await page.evaluate(() => {
const el = document.getElementById('test');

if (!el) {
throw new Error('#test not found');
}

return window.getComputedStyle(el).getPropertyValue('display');
});

expect(display).toBe('grid');

await server.close();
});
11 changes: 11 additions & 0 deletions test/tools-postcss/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import 'tailwindcss/utilities.css';

function className() {
return 'flex';
}

const root = document.getElementById('root');
const element = document.createElement('div');
element.id = 'test';
element.className = className();
root.appendChild(element);