Next.js
examples/example-nextjs configures
StyleX for the Next.js App Router using the Babel and PostCSS plugins. Babel
compiles StyleX in JS/TS, and the PostCSS plugin replaces the @stylex
directive with the generated CSS.
Install
- npm
- pnpm
- yarn
- bun
npm install --save-dev @stylexjs/babel-plugin @stylexjs/postcss-plugin
pnpm add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin
yarn add -D @stylexjs/babel-plugin @stylexjs/postcss-plugin
bun add -D @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 = {
presets: ['next/babel'],
plugins: [
[
'@stylexjs/babel-plugin',
{
dev,
runtimeInjection: false,
genConditionalClasses: true,
treeshakeCompensation: true,
aliases: { '@/*': [path.join(__dirname, '*')] },
unstable_moduleResolution: { type: 'commonJS' },
// ... other StyleX configuration
},
],
],
};
Ensure next/babel runs alongside the StyleX plugin so both app and component
code are transformed.
CSS entrypoint
Import a CSS file in your root layout component file, so that your entire application can have a single atomic CSS file.
Include the @stylex directive within this CSS file.
/* app/globals.css */
@layer resets {
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
}
@stylex;
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 for StyleX.
Configure the include option with glob patterns to look for all source files that may contain StyleX styles.
const babelConfig = require('./babel.config');
module.exports = {
plugins: {
'@stylexjs/postcss-plugin': {
include: [
// when using a src folder:
'src/**/*.{js,jsx,ts,tsx}',
// app router:
'app/**/*.{js,jsx,ts,tsx}',
// pages router:
'pages/**/*.{js,jsx,ts,tsx}',
// other top-level folders:
'components/**/*.{js,jsx,ts,tsx}',
],
babelConfig: {
babelrc: false,
parserOpts: { plugins: ['typescript', 'jsx'] },
plugins: babelConfig.plugins,
},
useCSSLayers: true,
},
autoprefixer: {},
},
};
You can skip Babel transforms for anything other than StyleX in your PostCSS configuration to speed up CSS generation.
Using the configurations
Once you define these configuration files, Next.js will automatically use Babel and PostCSS without any changes to your
next.config.js file. Since Next.js 16.0.3, this works with both Webpack and Turbopack.