辣评前端样式体系重构(七)

 

样式体系重构概述

前端样式体系的重构是为了提升代码可维护性、统一设计风格、优化构建性能。

重构目标

  • 统一设计规范
  • 提升代码可维护性
  • 优化构建性能
  • 支持主题切换

Element Plus 集成

安装和配置

npm install element-plus

按需导入

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App)
app.use(ElementPlus)

主题系统设计

CSS 变量定义

:root {
  --primary-color: #409eff;
  --success-color: #67c23a;
  --warning-color: #e6a23c;
  --danger-color: #f56c6c;
  --error-color: #f56c6c;
  --info-color: #909399;
  
  --text-primary: #303133;
  --text-regular: #606266;
  --text-secondary: #909399;
  --text-placeholder: #a8abb2;
  
  --border-color: #dcdfe6;
  --border-light: #ebeef5;
  --border-lighter: #f5f7fa;
  
  --bg-color: #ffffff;
  --bg-light: #f5f7fa;
  --bg-lighter: #fafafa;
}

/* 暗色主题 */
[data-theme="dark"] {
  --primary-color: #409eff;
  --text-primary: #e4e7eb;
  --bg-color: #1f1f1f;
  --bg-light: #2c2c2c;
}

Sass 变量管理

变量定义

// colors.scss
$primary: #409eff;
$success: #67c23a;
$warning: #e6a23c;
$danger: #f56c6c;

// spacing.scss
$spacing-xs: 4px;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;
$spacing-xl: 32px;

// typography.scss
$font-size-xs: 12px;
$font-size-sm: 14px;
$font-size-base: 16px;
$font-size-lg: 18px;
$font-size-xl: 20px;

// breakpoints.scss
$breakpoint-xs: 480px;
$breakpoint-sm: 768px;
$breakpoint-md: 1024px;
$breakpoint-lg: 1280px;

混合宏

// mixins.scss
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@mixin responsive($breakpoint) {
  @if $breakpoint == 'xs' {
    @media (max-width: $breakpoint-xs) {
      @content;
    }
  } @else if $breakpoint == 'sm' {
    @media (max-width: $breakpoint-sm) {
      @content;
    }
  }
}

样式优化与性能

CSS 分割

// vite.config.js
export default {
  build: {
    cssCodeSplit: true,
    rollupOptions: {
      output: {
        manualChunks: {
          'element-plus': ['element-plus']
        }
      }
    }
  }
}

样式预处理

// 避免深层嵌套
.component {
  &__header {
    padding: $spacing-md;
  }
  
  &__content {
    margin-top: $spacing-lg;
  }
  
  &__footer {
    border-top: 1px solid $border-color;
  }
}

Vite 分包优化

分包配置

export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          'vue': ['vue'],
          'element-plus': ['element-plus'],
          'utils': ['./src/utils/index.ts']
        }
      }
    }
  }
}

总结

样式体系的重构提升了代码质量和开发效率。

本文遵守 Attribution-NonCommercial 4.0 International 许可协议。 Attribution-NonCommercial 4.0 International