Taro + Scss + Tailwind CSS 初体验

1,630 阅读4分钟

前言

Taro社区提供的css in js 方案,在Taro3上面基本都存在问题,没法使用。综合各种因素,我最终选择Scss + Tailwind CSS作为项目的CSS解决方案

Scss

Scss的使用这里不再赘述,掘金上面也有很多相关文章

Taro 默认支持scss,参考配置。如果使用taro cli创建项目,选择CSS处理器为SASS可以开箱即用

image.png

CSS Modules

React 中使用Scss 推荐使用CSS Modules,样式有局部作用域,不会产生全局污染

导入在文件中的CSS Modules 是any类型,没法解析出样式表的的类型,在VSCode中可以使用CSS Modules插件,可以实现类名提示和跳转(如果存在同名类只会跳转到第一个,只能在文件里面重新找😆,目前找不到解决方案,但总比没有好)

20231226214757.gif

Tailwind CSS

Taro中引入Tailwind CSS需要使用社区的方案

IDE提示

如果Tailwind CSS只是一套css类的集合,那得经常去查文档才能使用,搭配Tailwind CSS IntelliSense 这个VSCode插件才是正确的使用方式。

看一下Tailwind CSS IntelliSense的提示效果

  • className中输入提示效果 image.png
  • 自动检测冲突值

image.png

  • 鼠标悬浮到类名上展示类样式 image.png

  • 自定义类名也能根据匹配值转化样式

image.png

样式复用

元素样式不复杂时,可以直接在className中写Tailwind类,就不用费脑子想类名了

若样式比较复杂,推荐添加一个新的类,在类中使用@apply 引用Tailwind类,举个例子对比一下

  1. 直接写样式:

image.png

  1. 引用tailwind类:

image.png

可以看到,Tailwind类可读性很高,容易记住,并且能减少很多行代码。


使用@apply规则的时候,如果VSCode提示以下错误

image.png

可以添加自定义css规则,让VSCode能识别Tailwind CSS的@aplly@screen等:

  1. 在.vscode中添加settings.json,加入以下配置
{
  ...
  "css.customData": [".vscode/tailwind.json"]
}
  1. 在.vscode中添加tailwind.json,内容如下,其中description和references是描述信息,只有name是必要的
{
  "version": 1.1,
  "atDirectives": [
    {
        
      "name": "@tailwind",
      "description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",
      "references": [
        {
          "name": "Tailwind Documentation",
          "url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"
        }
      ]
    },
    {
      "name": "@apply",
      "description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.",
      "references": [
        {
          "name": "Tailwind Documentation",
          "url": "https://tailwindcss.com/docs/functions-and-directives#apply"
        }
      ]
    },
    {
      "name": "@responsive",
      "description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n  .alert {\n    background-color: #E53E3E;\n  }\n}\n```\n",
      "references": [
        {
          "name": "Tailwind Documentation",
          "url": "https://tailwindcss.com/docs/functions-and-directives#responsive"
        }
      ]
    },
    {
      "name": "@screen",
      "description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n  /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n  /* ... */\n}\n```\n",
      "references": [
        {
          "name": "Tailwind Documentation",
          "url": "https://tailwindcss.com/docs/functions-and-directives#screen"
        }
      ]
    },
    {
      "name": "@variants",
      "description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n   .btn-brand {\n    background-color: #3182CE;\n  }\n}\n```\n",
      "references": [
        {
          "name": "Tailwind Documentation",
          "url": "https://tailwindcss.com/docs/functions-and-directives#variants"
        }
      ]
    }
  ]
}

可以了,现在@apply有描述,还能点击链接去官网查看详情,下次遇到类似的问题都可以这样解决 image.png

设置默认单位为px

Tailwind CSS有自己的一套设计规范,比如m-1代表margin: 0.25rem; /* 4px */

如果想让m-1代表margin: 1px,即让数字的单位px,需要在tailwind.config.js配置theme的spacing属性:

module.exports = {
  theme: {
    extend: {},
    // 100以内的单位都转成px,不要设置太多,避免Tailwind CSS IntelliSense提示缓慢,较大的值可以使用[-px]
    spacing: Array.from({ length: 100 }).reduce((map, _, index) => {
      map[index] = `${index}px`
      return map
    }, {}),
  }
}

这种方式对于尺寸类(如m、p、size、w、h)都能生效,其他的比如text就无法生效了。

更为通用的方式是设置为-[px],如text-[14px]就转换为font-size: 14px

添加自定义原子类

Tailwind CSS的flex原子类基本覆盖所有flex布局内容,但是想让子元素水平垂直居中布局,还是得使用flex items-center justify-center这三个类,确实有点长。如果想自定义一个类,集合这个三个类的功能,可以添加在tailwind.config.js中添加自定义原子类

import plugin from 'tailwindcss/plugin'
module.exports = {
  plugins: [
    plugin(function ({ addComponents }) {
      addComponents({
        '.flex-center': {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }
      })
    })
  ]
}

这样,使用flex-center就能实现水平垂直居中了,VSCode也有类样式提示

image.png

\color{red}{注}: 官网中还有通过@layer components添加自定义类的实现,但是VSCode不会有样式提示,而且需要每个文档单独引入,通过scss全局引入的话,在小程序端会报错,所以就不采取这个方案了。

添加自定义颜色

比较简单,直接修改tailwind.config.js配置

module.exports = {
  theme: {
    colors: {
      // 主题颜色
      primary: '#1d9bf0'
    }
  }
}

ok,颜色相关的类,都可以使用这个颜色值了,是不是很厉害?

背景色

image.png

文字颜色

image.png

边框颜色

image.png

总结

Taro框架上面,Tailwind CSS目前还是最好用的原子CSS框架,只需要花费少量的时间学习,就能提高编写样式的效率,同时保证代码可读性。

参考项目