Set up Master CSS in Next.js
Guide to setting up Master CSS in your Next.js project.
Master CSS Static Extraction integrates build tools to scan project source code, extract class names, generate CSS rules, and write them into a virtual CSS module.
Zero runtime
Generate virtual CSS modules at build time
Semi-dynamic
Scan all source code to extract class names
Cross-page caching
Download the CSS bundle for all pages at once
Create a Next.js project
If you don't have a Next.js project, create one first. It's recommended to refer to Create Next App.
npm create next-app --app --tscd my-app
Create a configuration file
Run the command to create a master.css.js file.
npm create @master/css@rc
Install Master CSS
Install the Master CSS extractor into your project via package managers.
npm i @master/css.webpack@rc
Set up CSS extractor
- Define a
webpackConfig
and add aMasterCSSExtractorPlugin
innext.config.js
- Concat the
webpackConfig.plugins
MasterCSSExtractorPlugin
cannot be created directly in nextConfig
, this will result in multiple instances.
const { MasterCSSExtractorPlugin } = require('@master/css.webpack') /** @type {import('webpack').Configuration} */const webpackConfig = { plugins: [ new MasterCSSExtractorPlugin() ] } /** @type {import('next').NextConfig} */const nextConfig = { webpack: (config) => { config.plugins.push(...webpackConfig.plugins) return config } }module.exports = nextConfig
Import virtual CSS module
Import the virtual CSS module virtual:master.css
into the app/globals.css
.
@import 'virtual:master.css'; …
Launch server
Run npm run dev
to start your Next.js development server
npm run dev
Start using Master CSS
Now style your first element using Master CSS syntax!
export default function Home() { return ( <h1 className="italic m:12x fg:strong font:40 font:heavy">Hello World</h1> )}
Open your browser to watch the changes.