Appearance
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
bash
bun add -D unocss @unocss/webpack
配置
在项目根目录创建 uno.config.ts
文件。
ts
import {
defineConfig,
presetAttributify,
presetIcons,
presetWebFonts,
presetWind3
} from 'unocss'
export default defineConfig({
presets: [
presetWind3(),
// ...
],
})
添加插件
然后通过 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
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
使用方法
使用 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)
若要支持热模块替换(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
中将 target
至少提升到 es2015
。
默认情况下,不支持使用 .js
扩展名的文件。将文件扩展名更改为 .jsx
,或者尝试在配置中使用 include: /\.js$/
包含 .js
文件。了解更多。