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.