前端脚手架 webpack 迁移 Vite2 踩坑实践

codexu -
前端脚手架 webpack 迁移 Vite2 踩坑实践
项目背景

首先介绍一下我的个人开源项目 X-BUILD ,是一款前端脚手架,从2017年2月至今已有4年多的时间,目前我正在针对 vue3 做一套全新的版本,全面使用 Vite 作为构建工具,在这个过程中遇到的一些坑和优势分享给大家。

另外如果对我的脚手架有兴趣尝试,可以参考说明文档。

Vite 迁移指南

刚刚开始开发 v6.0 版本时,对 Vite 不是很了解,所以依然采用了 Vue-CLI 4.5 进行模板的基本搭建。后续开发过程中,逐步对 Vite 产生了更多的了解,有很多新的特性很不错,所以从 v6.1 开始,全面迁移至 Vite2 作为模板的构建工具。

ESLint

Vite 目前还没有提供灵活的配置选项,默认创建的项目并不支持自动配置好的 ESLint 功能,所以需要手动配置,这块也是我花费迁移时间最多的一块。在 awesome-vite 中发现了一个配置 ESLint 的插件 - vite-eslint,但我不知道要使用的 Airbnb 方案如何配置,所以这一块我还是采用了手动配置的方式。

ESLint 相关依赖eslint@7.32.0eslint-config-airbnb-base@14.2.1 (Airbnb 基础规则的 ESLint 插件)eslint-plugin-import@2.24.2eslint-plugin-vue"@7.17.0Prettier 相关依赖prettier@2.3.2eslint-config-prettier@8.3.0eslint-plugin-prettier@4.0.0ESLint 规则和 Prettier 规则存在冲突的情况,eslint-config-prettier 这个插件就是禁用所有格式相关的 ESLint 规则,也就是说格式规则这块由 Prettier 来处理。配置文件

.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: ['plugin:vue/vue3-essential', 'airbnb-base', 'plugin:prettier/recommended'],
  parserOptions: {
    ecmaVersion: 12,
    parser: '@typescript-eslint/parser',
    sourceType: 'module',
  },
  plugins: ['vue', '@typescript-eslint'],
  rules: {
    'import/no-unresolved': 'off',
    'import/extensions': 'off',
    'import/no-absolute-path': 'off',
    'import/no-extraneous-dependencies': 'off',
    'vue/no-multiple-template-root': 'off',
    'no-param-reassign': [
      'error',
      {
        props: true,
        ignorePropertyModificationsFor: ['state', 'config'],
      },
    ],
  },
  settings: {},
};


复制代码

.prettierrc

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 88,
  "singleQuote": true,
  "trailingComma": "all",
  "bracketSpacing": true,
  "semi": true
}
复制代码

至此,ESLint 就可以正常使用了,如果有特殊要求可以在配置文件中手动增加 Rules。

Stylelint

虽然我已经打算全面拥抱 Tailwind.css,但难免个别情况我们要单独使用 CSS 来实现,那么一个标准的编码风格校验就显得尤为重要。

相关依赖stylelint@13.13.1stylelint-config-standard@22.0.0 (Stylelint 的推荐配置)stylelint-config-prettier@8.0.2stylelint-config-recess-order@2.5.0 (属性排序)Stylelint 与 ESLint 类似,都与 Prettier 规则有冲突,stylelint-config-prettier 可以解决这些冲突。配置文件
module.exports = {
  extends: [
    'stylelint-config-standard', 
    'stylelint-config-prettier', 
    'stylelint-config-recess-order',
  ],
  plugins: ['stylelint-scss'],
  rules: {
        // ...
  },
};
复制代码
如果你使用 Sass/Scss 需要安装插件 stylelint-scss。Tailwind.css

Tailwind 现在的评价褒贬不一,我个人尝试之后觉得不错,在团队内也进行了推广,目前已经成为团队技术栈的一部分。目前在项目中使用的是 Postcss 兼容性方式,尽管使用的 v2.2 版本,也无法使用 JIT 模式,这是由于目前使用 @vue/cli 4.5 之前的版本使用的是 Postcss 7,想要升级比较麻烦,或者等待@vue/cli 5.0 版本(目前是测试版)。但 vite2 恰巧已经使用了 Postcss 8,问题迎刃而解。

JIT 模式

Tailwind CSS 2.0 正式上线的 Just-in-Time (简称 JIT)编译器,可以在写 HTML 时及时编译 CSS,大幅缩短编译时间,以及缩小产生的文件大小,它具备以下特点:

超快速的编译时间:原本Tailwind CLI编译需要3-8秒,在 JIT模式 下仅需 0.8秒直接使用任意Variants:不用再烦恼需不需要开 activefocusdisabled 等。任意值CSS class:可以直接在HTML里写像 h-[13px] 这样的class,将会自动生成。在开发和生产环境编译出一样的CSS:不需要烦恼上线后会不会有 class 灵异的消失。相关依赖vitawind@1.2.8Vitawind 是一个在 Vite 上可以用几步就可以安装和配置好的 Tailwind CSS 的工具。配置文件

你可以按照官网的方式快速的进行配置,或者通过手动的方式配置:

创建 src/styles/tailwind.css 文件

@tailwind base;
@tailwind components;
@tailwind utilities;
复制代码

在 main.ts 中引入:

import '@/styles/tailwind.css';
复制代码

在根目录创建 tailwind.config.js:

module.exports = {
  mode: 'jit',
  purge: ['index.html','./src/**/*.{js,jsx,ts,tsx,vue,html}'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  plugins: [],
}
复制代码

至此,Tailwind 已经可以在项目中正常使用。

JIT 模式太香了,建议大家真正的尝试一段时间再对 Tailwind 做客观的评价。

组件库的自动导入

你是否还是按照下面这个步骤加载某些组件库中的组件?

通过 import { *** } from '***' 加载某些组件。通过 Vue.use(***) 去加载组件。引入组件库样式文件。如果你做按需加载,还需要使用 babel 插件支持。

如果是这样,那么我建议你替换成另一种更便捷的方式 unplugin-vue-components。

特点开箱即用地支持 Vue 2 和 Vue 3。支持 Vite、Webpack、Vue CLI、Rollup。Tree-shakable,只注册你使用的组件。文件夹名称作为命名空间。完整的 TypeScript 支持。流行的 UI 库的内置解析器。组件库支持

支持了市面上常见的组件库:

Ant Design VueElement PlusElement UIHeadless UIIDuxNaive UIPrime VueVantVEUIVarlet UIView UIVuetifyVueUse Components相关依赖unplugin-vue-components@0.14.9配置文件
import Components from 'unplugin-vue-components/vite';
import ViteComponents, {
  AntDesignVueResolver,
  ElementPlusResolver,
  VantResolver,
} from 'unplugin-vue-components/resolvers'

// vite.config.ts
plugins: [
  Components({
    resolvers: [
      AntDesignVueResolver(),
      ElementPlusResolver(),
      VantResolver(),
    ]
  })
]
复制代码

不需要手动引入组件的方式是不是很香?

环境变量

在开发过程中,通常分为三步,development(开发)、staging(预生产测试)、production(生产),在不同的环境下使用不同的变量和打包方式,这一点 Vite 也是支持的,不过与 Webpack 有一些出入:

process.env.VUE_APP_BASE_URL // webpack
import.meta.env.BASE_URL // vite
复制代码
Webpack 与 Vite 环境变量获取的方式不同。.env 文件的使用方式是一致的。vite 支持 TypeScript 智能提示,这需要你在 env.d.ts 中配置。别名配置

Vite 创建的项目并不能直接使用别名,例如 @ 操作符代表 src,可以通过下面的配置实现:

// vite.config.ts
resolve: {
  alias: {
    '@': resolve(__dirname, './src'),
  },
},
复制代码
SVG 图标

图标一直使用的是 svg 方案,通过 svg-sprite-loader 来加载项目中的 svg 文件,但这个 loader vite 是无法使用的,所以我们采用另一个方案:

相关依赖vite-plugin-svg-icons@1.0.4配置文件
// vite.config.ts
plugins: [
  viteSvgIcons({
    iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
    symbolId: 'icon-[dir]-[name]',
  }),
]
复制代码

在 main.ts 中引入

import 'virtual:svg-icons-register';
复制代码
组件

手写一个全局组件,方便调用,支持文件夹、颜色配置。

<script setup lang="ts">
import { computed, withDefaults, defineProps } from 'vue';

interface Props {
  prefix?: string;
  name?: string;
  color?: string;
}

const props = withDefaults(defineProps<Props>(), {
  prefix: 'icon',
  name: '',
  color: '#000',
});

const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>

<template>
  <svg aria-hidden="true">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>
复制代码
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

前端javascriptvue.jsnode.js

扩展阅读

加个好友,技术交流

1628738909466805.jpg