June 7, 2022 • ☕️ 2 min read
日本語

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

Copy
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.

unocss.config.ts
Copy
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

  1. Install parallel package for develop mode.
Copy
npm i -D npm-run-all
  1. Add scripts to package.json for uno.css’s compile.
package.json
Copy
{
  "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",
  }
}
  1. Add import "uno.css" to _app.tsx.
pages/_app.tsx
Copy
import "../styles/uno.css";
  1. Exclude uno.css from git targets.
.gitignore
Copy
src/styles/uno.css

Finish

Starting Next.js in development mode and production mode is the same.

Copy
# 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:

performance


Relative Posts

I migrated my homepage from GatsbyJS to Next.js

November 5, 2022

Combine Next.js + material-ui + styled-components with TypeScript

January 16, 2022

ThunderMiracle

Blog part of ThunderMiracle.com