likes
comments
collection
share

nextjs 与 unocss 最佳实践

作者站长头像
站长
· 阅读数 13

前言

作为一个前端开发来说,对于css,真是又爱又恨。可以用其实现各种炫酷的效果,但真的很难写。特别是使用 React 作为主要开发框架,有着各种各样的css写法。

你可以选择复古的引入css文件的方式,也可以使用css module的方式,也可以使用styled-components一把梭,也可以选择taiwindcss来不写cssReact就是有着这样的特点,没有固定的开发范式,社区的相关技术栈选择多到让人眩晕。

那今天就来讲一个更新的css写法,使用 Unocss

开始

这里我们直接用 nextjs + typescript, 一步到位

创建项目

yarn create next-app --typescript

安装依赖

yarn add @unocss/preset-uno @unocss/webpack unocss

更改 next.config.js

const UnoCSS = require('@unocss/webpack').default;
const presetUno = require("@unocss/preset-uno").default;

const nextConfig = {
  reactStrictMode: true,
  webpack: (config, context) => {
    config.plugins.push(UnoCSS({ presets: [presetUno()] }));

    if (context.buildId !== "development") {
      config.cache = false;
    }
    return config;
  },
}

module.exports = nextConfig

在根目录创建 unocss.config.ts

import {
  defineConfig,
  presetAttributify,
  presetIcons,
  presetUno,
  presetMini,
} from 'unocss';

export default defineConfig({
  presets: [
    presetUno(),
    presetAttributify(),
    presetMini()
  ],
});

在项目中使用

//index.tsx

export default function Home() {
  return (
    <div bg={'red'} color={'#ffffff'} text={'55px'} >Hello Unocss</div>
  )
}  

此时的页面: nextjs 与 unocss 最佳实践

这样的写css方式,我感觉还是挺新颖的,没有多余css文件,也没有过多的 styled 代码,也不需要像 taiwind 那样,没有样式需要在配置文件中自定义。

可能遇到的问题

  • Typescript errors: Property xxx does not exist on type 解决方法:
  1. 在根目录创建 shims.d.ts 文件
  2. 写入内容
import * as React from 'react'
declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // 在这里写入你使用的属性,例如:
    flex?: boolean
    relative?: boolean
    text?: string
    grid?: boolean
    before?: string
    after?: string
    shadow?: boolean
    w?: string
    h?: string
  }
}