Set up Master CSS in Next.js
Guide to setting up Master CSS in your Next.js project.
Master CSS Progressive Rendering scans the rendered HTML ahead of time, server-side or at build time, generates the corresponding CSS rules for each page, and defer loads the runtime engine to keep track of the dynamic class names.
Faster page loading
Non-rendering-blocking internal CSS and defer loading
Fully automatic
Capture any program-generated class names
CSS encapsulation
Only ship the page-used CSS instead of the whole site
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 Master CSS React into your project via package managers.
npm i @master/css.react@rc @master/css-cli@rc
Set up CSS runtime engine
Register Master CSS Runtime with official CSSRuntimeProvider
and provide instance context.
import './globals.css'import CSSRuntimeProvider from '@master/css.react' import config from '../master.css' export const metadata = { title: 'Create Next App', description: 'Generated by create next app',}export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en" hidden={process.env.NODE_ENV === 'development'}> <body> <CSSRuntimeProvider config={config}> {children} </CSSRuntimeProvider> </body> </html> )}
Set up Master CSS renderer
Statically generate CSS for each .html
page after next build
using the Master CSS Render CLI.
Next.js 13 has deprecated getInitialProps
, and there is no alternative, so now only static output is supported.
{ "scripts": { "dev": "next dev", "build": "next build", "build": "next build && mcss render \".next/**/*.html\"", "start": "next start", "lint": "next lint" }}
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.