vite项目初始化实践

19

vite项目初始化

  • 使用官方vite模板初始化
pnpm create vite my-app --template react-swc-ts
  • 配置.vscode

    {
      "prettier.enable": false,
      "editor.formatOnSave": false,
      "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
        "source.fixAll.stylelint": true,
        "source.organizeImports": false
      },
      "eslint.validate": [
        "javascript",
        "javascriptreact",
        "typescript",
        "typescriptreact",
        "html",
        "markdown",
        "json",
        "jsonc",
        "yaml"
      ],
      "stylelint.validate": [
        "css",
        "less",
        "scss"
      ]
    }
    
  • 配置eslint

    pnpm i -D @antfu/eslint-config-react eslint eslint-config-standard-jsx
    
    • 配置.eslintrc.cjs

      module.exports = {
        root: true,
        extends: ['standard-jsx', '@antfu/eslint-config-react', '@unocss'],
        rules: {
          'react/prop-types': 'off',
          'unused-imports/no-unused-imports': 'error',
        },
        settings: {
          react: {
            version: 'detect',
          },
        },
      }
      
  • 配置commitlint

    pnpm i -D @commitlint/cli @commitlint/config-conventional
    
    • 配置commitlint.config.cjs

      module.exports = { extends: ['@commitlint/config-conventional'] }
      
  • 配置stylelint

    pnpm i -D stylelint stylelint-config-standard-scss stylelint-stylistic
    
    • 配置stylelint.config.cjs

      module.exports = {
        extends: ['stylelint-config-standard-scss', 'stylelint-stylistic/config'],
        rules: {
          'selector-pseudo-class-no-unknown': [true, {
            ignorePseudoClasses: ['global'],
          }],
          'color-function-notation': null,
        },
      }
      
  • 配置unocss

    • vscode安装UnoCSS插件
    pnpm i -D unocss @unocss/reset @unocss/eslint-config @iconify/utils
    

    @unocss/reset 是css原子集合,@unocss/eslint-config用于eslint格式化,在.eslintrc.cjs有引用,@iconify/utils用于实现利用unocss加载自定义icons

  • 配置unocss.config.ts

    pnpm i svgo
    

    svgo用于压缩自定义icons

    import { defineConfig, transformerDirectives, transformerVariantGroup } from 'unocss'
    import presetIcons from 'unocss/preset-icons'
    import type { Theme } from 'unocss/preset-uno'
    import presetUno from 'unocss/preset-uno'
    import { FileSystemIconLoader } from '@iconify/utils/lib/loader/node-loaders'
    import { optimize } from 'svgo'
    
    export default defineConfig<Theme>({
      presets: [
        presetUno(),    // uno预设
        presetIcons({    // icon预设与自定义icon引入
          collections: {
            icon: FileSystemIconLoader(        // FileSystemIconLoader用于加载自定义icons, 并配合svgo压缩
              'src/assets/icons',
              svg => optimize(svg, { multipass: true }).data,
            ),
          },
        }),
      ],
      transformers: [
        transformerDirectives(),
        transformerVariantGroup(),
      ],
      rules: [
        // 简化写法,如 border-border-secondary 可简化为 border-secondary
        [
          /^(text|border|b|fill|bg)-(.*)$/,
          ([, p1, p2], { theme }) => {
            if (p1 === 'b')
              p1 = 'border'
    
            const colorKey = `${p1}-${p2}`
            const colorValue = theme.colors?.[colorKey] as string
            if (!colorValue)
              return
    
            switch (p1) {
              case 'text':
                return { color: colorValue }
              case 'border':
                return { 'border-color': colorValue }
              case 'fill':
                return { fill: colorValue }
              case 'bg':
                return { 'background-color': colorValue }
            }
          },
        ],
      ],
    })
    
  • 配置vite.config.ts

    pnpm i -D @vitejs/plugin-react-swc vite-plugin-pages @vitejs/plugin-legacy
    

vite-plugin-pages用于实现约定式路由,@vitejs/plugin-legacy提供垫片,兼容低版本浏览器

import path from 'node:path'
import fs from 'node:fs/promises'
import react from '@vitejs/plugin-react-swc'
import { defineConfig } from 'vite'
import pages from 'vite-plugin-pages'
import legacy from '@vitejs/plugin-legacy'
import unocss from 'unocss/vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    unocss(),
    pages({
      importMode: 'async',
      exclude: ['**/components/*.tsx'],
    }),
    legacy({
      modernPolyfills: true,
      renderLegacyChunks: false,
    }),
    {
      name: 'after-write-bundle',
      apply: 'build',
      writeBundle: async ({ dir }) => {
        // 生产环境下删除 mockServiceWorker.js
        await fs.rm(path.resolve(dir, 'mockServiceWorker.js'))
      },
    },
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  build: {
    target: 'es2015',
  },
})

最后,

pnpm run dev

启动!