第五十二章-Vite插件-vite-plugin-windicss

1.说明

在Vite上单独使用Tailwind时,渲染速度很慢。

vite-plugin-windicssTailwind快20到100倍。

2.安装

yarn add vite-plugin-windicss --dev

3.创建Windicss配置文件

windicss的配置

tailwind的配置

tailwind.config.ts

import lineClamp from 'windicss/plugin/line-clamp';
import colors from 'windicss/colors';

import { defineConfig } from 'vite-plugin-windicss';
import { primaryColor } from './build/config/themeConfig';

export default defineConfig({
  darkMode: 'class',
  plugins: [lineClamp, createEnterPlugin()],
  theme: {
    extend: {
      colors: {
        ...colors,
        primary: primaryColor,
      },
      screens: {
        sm: '576px',
        md: '768px',
        lg: '992px',
        xl: '1200px',
        '2xl': '1600px',
      },
    },
  },
});

/**
 * Used for animation when the element is displayed
 * @param maxOutput The larger the maxOutput output, the larger the generated css volume
 */
function createEnterPlugin(maxOutput = 10) {
  const createCss = (index: number, d = 'x') => {
    const upd = d.toUpperCase();
    return {
      [`*> .enter-${d}:nth-child(${index})`]: {
        transform: `translate${upd}(50px)`,
      },
      [`*> .-enter-${d}:nth-child(${index})`]: {
        transform: `translate${upd}(-50px)`,
      },
      [`* > .enter-${d}:nth-child(${index}),* > .-enter-${d}:nth-child(${index})`]: {
        'z-index': `${10 - index}`,
        opacity: '0',
        animation: `enter-${d}-animation 0.4s ease-in-out 0.3s`,
        'animation-fill-mode': 'forwards',
        'animation-delay': `${(index * 1) / 10}s`,
      },
    };
  };
  const handler = ({ addBase }) => {
    const addRawCss = {};
    for (let index = 1; index < maxOutput; index++) {
      Object.assign(addRawCss, {
        ...createCss(index, 'x'),
        ...createCss(index, 'y'),
      });
    }
    addBase({
      ...addRawCss,
      [`@keyframes enter-x-animation`]: {
        to: {
          opacity: '1',
          transform: 'translateX(0)',
        },
      },
      [`@keyframes enter-y-animation`]: {
        to: {
          opacity: '1',
          transform: 'translateY(0)',
        },
      },
    });
  };
  return { handler };
}

3.创建配置文件

build\vite\plugin\windicss.ts

import type { Plugin } from 'vite';

import windiCSS from 'vite-plugin-windicss';

export function configWindiCssPlugin(): Plugin[] {
  return windiCSS({
    safelist: 'no-select',
    preflight: {
      enableAll: true,
    },
  });
}

4.应用配置

build\vite\plugin\index.ts

// ...
import { configWindiCssPlugin } from './windicss';

export function createVitePlugins(viteEnv: ViteEnv, isBuild: boolean) {
  // ...
  // vite-plugin-windicss
  vitePlugins.push(configWindiCssPlugin());
  return vitePlugins;
}

5.导入样式

src\main.ts

// ...
import '@virtual/windi.css';

// ...

上一章

第五十一章-vite插件-vite-plugin-svg-icon

下一章

第五十三章-Vite插件-vite-plugin-mock

# vben  vite 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×