Skip to main content

PostCSS Plugin

With certain build pipelines, the StyleX unplugin package may not be feasible. In such scenarios, the StyleX PostCSS plugin offers an easier and more compatible alternative.

The PostCSS plugin lets you decouple the transformation of your JS files with Babel and the generation of your CSS file.

Install

Start by installing the StyleX babel and postcss plugins:

npm install --save-dev @stylexjs/babel-plugin @stylexjs/postcss-plugin

Babel configuration

Create a babel.config.js file in your project root and add the StyleX Babel plugin to it.

const path = require('path');
const dev = process.env.NODE_ENV !== 'production';

module.exports = {
// ... other babel configuration
plugins: [
[
'@stylexjs/babel-plugin',
{
dev,
unstable_moduleResolution: { type: 'commonJS' },
// ... other StyleX configuration
},
],
],
};

Ensure that your JS source files are being transpiled by Babel using this configuration.

CSS entrypoint

Next, ensure that your application contains a single global CSS file that includes the @stylex directive:

@layer base {
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
/* other base styles */
}

@stylex;

If your build pipeline supports CSS imports, we recommend importing this in your root layout component, so that it is included for all routes of your app.

PostCSS configuration

Next, create a postcss.config.js that imports the Babel configuration to ensure that both the Babel and PostCSS plugins use the same configuration. Ensure that your build pipeline postprocesses your CSS with PostCSS using this config file.

Other than the babelConfig option, define one or more glob patterns for the include option to define all the files that may contain StyleX styles.

// postcss.config.mjs
import stylex from '@stylexjs/postcss-plugin';
import autoprefixer from 'autoprefixer';
import babelConfig from './babel.config.js';

export default {
plugins: [
stylex({
include: ['src/**/*.{ts,tsx}'],
useCSSLayers: true,
babelConfig: babelConfig,
}),
// ... other plugins
autoprefixer,
],
};

The PostCSS plugin will find all files that match the include glob patterns and transform them with the Babel plugin, collect the styles from them all, and replace the @stylex directive with the generated CSS. The PostCSS plugin uses per-file caching to speed up subsequent builds.

Examples

The storybook example in the StyleX repository shows one such usage of the PostCSS plugin.

The next.js example uses the same setup to integrate StyleX with Turbopack, which doesn't yet have a plugin API.