Vite 学习记录

Vite 是一种新型前端构建工具,显著提升前端开发体验,由一个开发服务器和一套构建指令组成

预构建 它们可以提高页面加载速度,并将 CommonJS / UMD 转换为 ESM 格式。预构建这一步由 esbuild 执行,这使得 Vite 的冷启动时间比任何基于 JavaScript 的打包器都要快得多。

  1. 安装
    npm create vite@latest
  2. 构建一个 Vite + Vue 项目
    npm create vite@latest my-vue-app --template vue

使用插件

  1. 安装插件
  2. 在 vite.config.js 引入插件
1
2
3
4
5
6
7
8
9
10
11
// vite.config.js
import legacy from "@vitejs/plugin-legacy";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [
legacy({
targets: ["defaults", "not IE 11"],
}),
],
});

plugins 也可以接受包含多个插件作为单个元素的预设。这对于使用多个插件实现的复杂特性(如框架集成)很有用。该数组将在内部被扁平化。

使用 enforce 修饰符来强制插件的位置:
pre:在 Vite 核心插件之前调用该插件
默认:在 Vite 核心插件之后调用该插件
post:在 Vite 构建插件之后调用该插件

1
2
3
4
5
6
7
8
9
10
11
12
// vite.config.js
import image from "@rollup/plugin-image";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [
{
...image(),
enforce: "pre",
},
],
});

默认情况下插件在开发 (serve) 和生产 (build) 模式中都会调用。如果插件在服务或构建期间按需使用,请使用 apply 属性指明它们仅在 ‘build’ 或 ‘serve’ 模式时调用:

1
2
3
4
5
6
7
8
9
10
11
12
// vite.config.js
import typescript2 from "rollup-plugin-typescript2";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [
{
...typescript2(),
apply: "build",
},
],
});