tailwindcss在项目中的使用步骤记录

在已有的项目中使用tailwindcss,其步骤如下:

1、安装npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

"devDependencies": {
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.21",
    "tailwindcss": "^3.2.6"
}

2、运行npx tailwindcss init会在项目中生成一个tailwind.config.cjs文件。文件结构和配置如下:

// /** @type {import('tailwindcss').Config} */
const colors = require('tailwindcss/colors')
module.exports = {
  purge: ["./{src,Component}/**/*.{ts,tsx,jsx,js}"],
  darkMode: `media`, // or 'media' or 'class'
  theme: {
    colors: {
      transparent: 'transparent',
      current: 'currentColor',
      black: colors.black,
      white: colors.white,
      gray: colors.coolGray,
      indigo: colors.indigo,
      red: colors.rose,
      yellow: colors.amber,
      green: colors.emerald,
      purple: colors.violet,  
      blue: colors.blue,    
      blueInit: {
        light: '#85d7ff',
        DEFAULT: '#1fb6ff',
        dark: '#009eeb',
      },
      pink: {
        light: '#ff7ce5',
        DEFAULT: '#ff49db',
        dark: '#ff16d1',
      }
    }
  },
  variants: {
    extend: {
      borderColor: ['focus-visible'],
      opacity: ['disabled'],
    }
  },
  plugins: [],
}

3、在项目中新建postcss.config.cjs

module.exports = {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    }
}

4、新建一个样式文件:index.css,文件内容如下:

@tailwind base;
@tailwind components;
@tailwind utilities;

5、运行得到编译后的index.css文件。--watch 监听文件更新,相当于热加载。

npx tailwindcss -o ./index.css --watch

7、将index.css 导入项目入口文件【如index.html;main.js;index.tsx】。

<link href="/index.css" rel="stylesheet">
或
import './index.css'

8、使用示例

<h1 className="flex text-3xl font-bold underline text-green-500">Hello, ZhangSan.</h1>
<button className="py-2 px-4 bg-red-500 text-blue-dark font-semibold rounded-lg shadow-md">按钮</button>
<h2 className="text-blue-500">你好</h2>

9、合并运行,安装依赖"npm-run-all": "^4.1.5"

"scripts": {
    "dev": "run-p dev:*",
    "dev:css": "tailwindcss -o ./index.css --watch",
    "dev:server": "vite"
},
posted on 2023-03-24 20:59  羽丫头不乖  阅读(312)  评论(0)    收藏  举报