Vite构建工具深度解析


Vite构建工具深度解析

Vite是新一代前端构建工具,凭借原生ES模块和esbuild预构建,实现了极速的开发体验。相比Webpack,Vite在开发环境下几乎不需要等待就能启动。本文将深入介绍Vite的工作原理和高级配置。

一、核心原理

// Vite开发模式:基于原生ESM
// 浏览器直接请求ES模块,Vite按需编译

// 传统打包工具:先打包所有模块,再启动服务器
// Vite:先启动服务器,按请求编译对应模块

// 1. 依赖预构建 - 使用esbuild(比Webpack快10-100倍)
// node_modules中的依赖被预构建为ESM格式
// 多个文件合并为一个,减少请求次数

// 2. 源码按需编译
// 只编译当前页面用到的组件

// 3. HMR - 热模块替换
// 精确更新修改的模块,不影响其他模块

二、基础配置

// vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
  plugins: [vue()],
  
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
  
  server: {
    port: 3000,
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        changeOrigin: true,
        rewrite: function(path) { return path.replace(/^\/api/, ""); },
      },
    },
  },
  
  build: {
    outDir: "dist",
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ["vue", "vue-router", "pinia"],
        },
      },
    },
  },
});

三、插件开发

// 自定义Vite插件
function myPlugin() {
  return {
    name: "my-plugin",
    
    // 构建开始前
    buildStart: function() {
      console.log("Build started");
    },
    
    // 转换模块
    transform: function(code, id) {
      if (id.endsWith(".md")) {
        // 将Markdown转为Vue组件
        return transformMarkdown(code);
      }
    },
    
    // 配置HMR
    handleHotUpdate: function(ctx) {
      if (ctx.file.endsWith(".md")) {
        ctx.server.ws.send({
          type: "custom",
          event: "md-update",
          data: { file: ctx.file },
        });
      }
    },
  };
}

// 使用插件
export default defineConfig({
  plugins: [myPlugin()],
});

四、环境变量与模式

// .env.development
VITE_API_URL=http://localhost:8080
VITE_APP_TITLE=开发环境

// .env.production
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=生产环境

// 代码中使用
console.log(import.meta.env.VITE_API_URL);
console.log(import.meta.env.MODE);  // development or production

// 类型声明 - env.d.ts
interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  readonly VITE_APP_TITLE: string;
}
interface ImportMeta {
  readonly env: ImportMetaEnv;
}

Vite代表了前端构建工具的发展方向,它利用浏览器原生ES模块能力和esbuild的极致性能,为开发者提供了前所未有的开发体验。如果你的项目还在使用Webpack,可以考虑迁移到Vite,体验极速的开发反馈。


0.054110s