Tailwind CSS 可以与各种现代前端框架完美配合。本节将详细介绍如何将 Tailwind CSS 集成到 React、Vue 和 Angular 等主流框架中,并介绍相关的最佳实践。

React 集成

基础配置

  1. # 创建 React 项目
  2. npx create-react-app my-app --template typescript
  3. # 安装 Tailwind CSS
  4. npm install -D tailwindcss postcss autoprefixer
  5. # 初始化 Tailwind CSS
  6. npx tailwindcss init -p
  1. // tailwind.config.js
  2. module.exports = {
  3. content: [
  4. "./src/**/*.{js,jsx,ts,tsx}",
  5. ],
  6. theme: {
  7. extend: {},
  8. },
  9. plugins: [],
  10. }
  1. /* src/index.css */
  2. @tailwind base;
  3. @tailwind components;
  4. @tailwind utilities;

组件开发

  1. // src/components/Button.tsx
  2. interface ButtonProps {
  3. variant?: 'primary' | 'secondary';
  4. size?: 'sm' | 'md' | 'lg';
  5. children: React.ReactNode;
  6. }
  7. const Button: React.FC<ButtonProps> = ({
  8. variant = 'primary',
  9. size = 'md',
  10. children
  11. }) => {
  12. const baseStyles = 'rounded-lg font-medium transition-colors';
  13. const variants = {
  14. primary: 'bg-blue-500 text-white hover:bg-blue-600',
  15. secondary: 'bg-gray-500 text-white hover:bg-gray-600'
  16. };
  17. const sizes = {
  18. sm: 'px-3 py-1.5 text-sm',
  19. md: 'px-4 py-2 text-base',
  20. lg: 'px-6 py-3 text-lg'
  21. };
  22. return (
  23. <button className={`${baseStyles} ${variants[variant]} ${sizes[size]}`}>
  24. {children}
  25. </button>
  26. );
  27. };
  28. export default Button;

样式组织

  1. // src/styles/components.ts
  2. export const buttonStyles = {
  3. base: 'rounded-lg font-medium transition-colors',
  4. variants: {
  5. primary: 'bg-blue-500 text-white hover:bg-blue-600',
  6. secondary: 'bg-gray-500 text-white hover:bg-gray-600'
  7. },
  8. sizes: {
  9. sm: 'px-3 py-1.5 text-sm',
  10. md: 'px-4 py-2 text-base',
  11. lg: 'px-6 py-3 text-lg'
  12. }
  13. };

Vue 集成

项目配置

  1. # 创建 Vue 项目
  2. npm init vue@latest
  3. # 安装依赖
  4. npm install -D tailwindcss postcss autoprefixer
  5. # 初始化配置
  6. npx tailwindcss init -p
  1. // tailwind.config.js
  2. module.exports = {
  3. content: [
  4. "./index.html",
  5. "./src/**/*.{vue,js,ts,jsx,tsx}",
  6. ],
  7. theme: {
  8. extend: {},
  9. },
  10. plugins: [],
  11. }

组件示例

  1. <!-- src/components/BaseButton.vue -->
  2. <template>
  3. <button
  4. :class="[
  5. baseStyles,
  6. variants[variant],
  7. sizes[size]
  8. ]"
  9. >
  10. <slot></slot>
  11. </button>
  12. </template>
  13. <script setup lang="ts">
  14. interface Props {
  15. variant?: 'primary' | 'secondary';
  16. size?: 'sm' | 'md' | 'lg';
  17. }
  18. const props = withDefaults(defineProps<Props>(), {
  19. variant: 'primary',
  20. size: 'md'
  21. });
  22. const baseStyles = 'rounded-lg font-medium transition-colors';
  23. const variants = {
  24. primary: 'bg-blue-500 text-white hover:bg-blue-600',
  25. secondary: 'bg-gray-500 text-white hover:bg-gray-600'
  26. };
  27. const sizes = {
  28. sm: 'px-3 py-1.5 text-sm',
  29. md: 'px-4 py-2 text-base',
  30. lg: 'px-6 py-3 text-lg'
  31. };
  32. </script>

自定义指令

  1. // src/directives/tailwind.ts
  2. import { DirectiveBinding } from 'vue'
  3. export const vTailwind = {
  4. mounted(el: HTMLElement, binding: DirectiveBinding) {
  5. const value = binding.value
  6. if (typeof value === 'string') {
  7. el.className = value
  8. } else if (typeof value === 'object') {
  9. el.className = Object.entries(value)
  10. .filter(([_, condition]) => condition)
  11. .map(([className]) => className)
  12. .join(' ')
  13. }
  14. },
  15. updated(el: HTMLElement, binding: DirectiveBinding) {
  16. // 同上
  17. }
  18. }

Angular 集成

项目设置

  1. # 创建 Angular 项目
  2. ng new my-app
  3. # 安装依赖
  4. npm install -D tailwindcss postcss autoprefixer
  5. # 初始化配置
  6. npx tailwindcss init
  1. // tailwind.config.js
  2. module.exports = {
  3. content: [
  4. "./src/**/*.{html,ts}",
  5. ],
  6. theme: {
  7. extend: {},
  8. },
  9. plugins: [],
  10. }

组件实现

  1. // src/app/components/button/button.component.ts
  2. import { Component, Input } from '@angular/core';
  3. @Component({
  4. selector: 'app-button',
  5. template: `
  6. <button [ngClass]="[
  7. baseStyles,
  8. variants[variant],
  9. sizes[size]
  10. ]">
  11. <ng-content></ng-content>
  12. </button>
  13. `
  14. })
  15. export class ButtonComponent {
  16. @Input() variant: 'primary' | 'secondary' = 'primary';
  17. @Input() size: 'sm' | 'md' | 'lg' = 'md';
  18. baseStyles = 'rounded-lg font-medium transition-colors';
  19. variants = {
  20. primary: 'bg-blue-500 text-white hover:bg-blue-600',
  21. secondary: 'bg-gray-500 text-white hover:bg-gray-600'
  22. };
  23. sizes = {
  24. sm: 'px-3 py-1.5 text-sm',
  25. md: 'px-4 py-2 text-base',
  26. lg: 'px-6 py-3 text-lg'
  27. };
  28. }

服务封装

  1. // src/app/services/tailwind.service.ts
  2. import { Injectable } from '@angular/core';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class TailwindService {
  7. combineClasses(...classes: (string | undefined)[]): string {
  8. return classes.filter(Boolean).join(' ');
  9. }
  10. getColorClass(color: string, variant: string = '500'): string {
  11. return `bg-${color}-${variant}`;
  12. }
  13. getTextClass(color: string, variant: string = '500'): string {
  14. return `text-${color}-${variant}`;
  15. }
  16. }

框架通用最佳实践

样式抽象

  1. // src/styles/theme.ts
  2. export const theme = {
  3. colors: {
  4. primary: {
  5. light: 'bg-blue-400',
  6. default: 'bg-blue-500',
  7. dark: 'bg-blue-600'
  8. },
  9. secondary: {
  10. light: 'bg-gray-400',
  11. default: 'bg-gray-500',
  12. dark: 'bg-gray-600'
  13. }
  14. },
  15. typography: {
  16. sizes: {
  17. sm: 'text-sm',
  18. base: 'text-base',
  19. lg: 'text-lg'
  20. }
  21. }
  22. };

工具函数

  1. // src/utils/tailwind.ts
  2. export function classNames(...classes: (string | undefined)[]) {
  3. return classes.filter(Boolean).join(' ');
  4. }
  5. export function createVariant(baseClass: string, variants: Record<string, string>) {
  6. return (variant: keyof typeof variants) =>
  7. classNames(baseClass, variants[variant]);
  8. }

类型支持

  1. // src/types/tailwind.ts
  2. export type Color =
  3. | 'primary'
  4. | 'secondary'
  5. | 'success'
  6. | 'warning'
  7. | 'danger';
  8. export type Shade =
  9. | '50'
  10. | '100'
  11. | '200'
  12. | '300'
  13. | '400'
  14. | '500'
  15. | '600'
  16. | '700'
  17. | '800'
  18. | '900';
  19. export type ColorClass = `bg-${Color}-${Shade}`;
  20. export type TextClass = `text-${Color}-${Shade}`;

性能优化

按需加载

  1. // tailwind.config.js
  2. module.exports = {
  3. content: [
  4. // 精确指定需要处理的文件
  5. "./src/components/**/*.{js,ts,jsx,tsx,vue}",
  6. "./src/pages/**/*.{js,ts,jsx,tsx,vue}",
  7. ],
  8. // 禁用未使用的核心插件
  9. corePlugins: {
  10. float: false,
  11. clear: false,
  12. objectFit: false
  13. }
  14. }

构建优化

  1. // webpack.config.js
  2. module.exports = {
  3. optimization: {
  4. splitChunks: {
  5. cacheGroups: {
  6. styles: {
  7. name: 'styles',
  8. test: /\.css$/,
  9. chunks: 'all',
  10. enforce: true
  11. }
  12. }
  13. }
  14. }
  15. }

最佳实践

  1. 集成原则

    • 遵循框架约定
    • 保持代码一致性
    • 合理的样式组织
  2. 开发建议

    • 组件抽象
    • 类型支持
    • 工具函数复用
  3. 性能考虑

    • 按需加载
    • 代码分割
    • 缓存优化
  4. 维护策略

    • 统一的样式规范
    • 组件文档
    • 版本控制