Skip to content

Next.js

// TODO: 鏈接到示例

開始使用 UnoCSS 和 Next.js。

設置

安裝

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

配置

在項目根目錄創建 uno.config.ts

ts
// uno.config.ts
import {
  defineConfig,
  presetAttributify,
  presetIcons,
  presetUno,
  presetWebFonts
} from 'unocss'

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

添加插件

然後通過 next.config.js 將 UnoCSS 作為 webpack 插件添加。

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

導入樣式表

然後在 _app.tsx 中導入 uno.css

tsx
// _app.tsx
import '@unocss/reset/tailwind.css'
import 'uno.css'

import type { AppProps } from 'next/app'

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

export default MyApp

使用

使用 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>
    </>
  )
}

熱模塊重載

要支持熱模塊重載(HMR),你必須禁用 webpack 的緩存。

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

故障排除

虛擬模塊錯誤

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

嘗試刪除 .next 目錄並重新啟動開發服務器。

其他

你可能需要在 tsconfig.json 中將目標版本至少提升到 es2015 以構建你的項目。

默認情況下不支持擴展名為 .js 的文件。將文件擴展名更改為 .jsx,或嘗試在配置中包含 js 文件,使用 include: /\.js$/瞭解更多

Released under the MIT License.