After reading Anthony Fu’s Reimagine Atomic CSS blog, I’m starting to want to use UnoCSS. Right now, I’m planning to migrate my HP & blog from GatsbyJS to Next.js, so I’m going to try to use UnoCSS in Next.js.
Official support
As of 7 June 2022, there is still no official support: there are no Next.js samples in the UnoCSS Github repository and there are no UnoCSS samples in Next.js too. Actually there is a webpack plugin in UnoCSS, but it seems that plugin is suffering the cache bug (https://github.com/unocss/unocss/issues/419), which causes HMR(hot module replacement) not working problem. I had no choice but to use unocss-cli instead.
tl;dr
You can use UnoCSS in Next.js by outputting css with unocss-cli and import the output css file into _app.tsx
. In develop mode, just start unocss-cli in watch mode and updates will happen automatically (HMR).
Steps
Install packages
npm i -D @unocss/cli @unocss/preset-attributify @unocss/preset-uno @unocss/preset-web-fonts
Basic settings of UnoCSS
Create a unocss.config.ts
in the root folder and put the following common
configuration in it.
import presetAttributify from "@unocss/preset-attributify";
import presetUno from "@unocss/preset-uno";
import presetWebFonts from "@unocss/preset-web-fonts";
import { defineConfig } from "unocss";
export default defineConfig({
presets: [
presetUno(),
presetAttributify(),
presetWebFonts({
provider: "google",
fonts: {
sans: "Roboto",
},
}),
],
});
Output css to uno.css
and import to Next.js
- Install parallel package for develop mode.
npm i -D npm-run-all
- Add scripts to package.json for
uno.css
’s compile.
{
"scripts": {
"dev:css": "unocss 'src/**/*.tsx' --out-file=src/styles/uno.css --watch",
"dev:next": "next dev",
"dev": "run-p dev:*",
"css": "unocss 'src/**/*.tsx' --out-file=src/styles/uno.css",
"build": "npm run css && next build",
}
}
- Add
import "uno.css"
to_app.tsx
.
import "../styles/uno.css";
- Exclude
uno.css
from git targets.
src/styles/uno.css
Finish
Starting Next.js in development mode and production mode is the same.
# develop
npm run dev
# production
npm run build
npm start
Now let’s use UnoCSS in Next.js!
Sample project is available here: next-unocss-cli
And you can check it out in the browser too: https://next-unocss.vercel.app/
LightHouse score: