Skip to content

Next.js

// TODO: Link zu Beispielen

Erste Schritte mit UnoCSS und Next.js.

Einrichtung

Installation

bash
pnpm add -D unocss @unocss/webpack
bash
yarn add -D unocss @unocss/webpack
bash
npm install -D unocss @unocss/webpack
bash
bun add -D unocss @unocss/webpack

Konfiguration

Erstellen Sie uno.config.ts im Stammverzeichnis Ihres Projekts.

ts
import {
  defineConfig,
  presetAttributify,
  presetIcons,
  presetWebFonts,
  presetWind3
} from 'unocss'

export default defineConfig({
  presets: [
    presetWind3(),
    // ...
  ],
})

Plugin hinzufügen

Fügen Sie dann UnoCSS als Plugin zu webpack über Ihre next.config.js hinzu.

js
// next.config.js
const UnoCSS = require('@unocss/webpack').default

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config) => {
    config.plugins.push(
      UnoCSS(),
    )
    return config
  },
}

module.exports = nextConfig

Stylesheets importieren

Importieren Sie dann uno.css in _app.tsx.

tsx
import type { AppProps } from 'next/app'
// _app.tsx
import '@unocss/reset/tailwind.css'

import 'uno.css'

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

export default MyApp

Verwendung

Stylen Sie Ihre Komponenten mit unocss!

tsx
/* index.tsx */
const Home: NextPage = () => {
  return (
    <>
      <main className="py-20 px-12 text-center flex flex-col items-center gap-20px">
        <span text="blue 5xl hover:red" cursor="default">Nextjs</span>
        <div className="i-carbon-car inline-block" text="4xl" />
        <button className="btn w-10rem">Button</button>
      </main>
    </>
  )
}

Hot Module Reload

Um HMR zu unterstützen, müssen Sie das Caching von webpack deaktivieren.

js
// next.config.js
const nextConfig = {
  reactStrictMode: true,
  webpack: (config) => {
+   config.cache = false
    config.plugins.push(UnoCSS())
    return config
  }
}

Fehlerbehebung

Fehler bezüglich virtuellem Modul

bash
Error: ENOENT: no such file or directory, open '.../_virtual_/__uno.css'

Versuchen Sie, das .next Verzeichnis zu löschen und den Dev-Server neu zu starten.

Andere

Möglicherweise müssen Sie Ihr Ziel in Ihrer tsconfig.json auf mindestens es2015 erhöhen, um Ihr Projekt zu erstellen.

Dateien mit der Erweiterung .js werden standardmäßig nicht unterstützt. Ändern Sie Ihre Dateierweiterungen zu .jsx oder versuchen Sie, js-Dateien in Ihrer Konfiguration mit include: /\.js$/ einzuschließen. Mehr erfahren.

Released under the MIT License.