Skip to content

UnoCSS Next.js Integration

// TODO: link to examples

Bắt đầu với UnoCSS và Next.js.

Cài đặt

Cài đặt

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

Cấu hình

Tạo uno.config.ts ở gốc dự án của bạn.

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

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

Thêm plugin

Sau đó thêm UnoCSS làm plugin cho webpack thông qua next.config.js của bạn.

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

Import bảng định kiểu

Sau đó import uno.css trong _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

Sử dụng

Định kiểu các thành phần của bạn với 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

Để hỗ trợ HMR bạn phải chọn không dùng bộ nhớ đệm của webpack.

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

Khắc phục sự cố

Lỗi liên quan đến mô-đun ảo

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

Thử xóa thư mục .next và khởi động lại máy chủ phát triển.

Khác

Bạn có thể cần nâng mục tiêu của mình lên ít nhất es2015 trong tsconfig.json để xây dựng dự án của bạn.

Các tệp có phần mở rộng .js không được hỗ trợ theo mặc định. Thay đổi phần mở rộng tệp của bạn thành .jsx hoặc thử bao gồm các tệp js trong cấu hình của bạn với include: /\.js$/. Tìm hiểu thêm.

Released under the MIT License.