Vite:下一代前端构建工具的快速指南

Vite 是 Vue.js 作者 Yuxi You 开发的新一代前端构建工具,以快速冷启动、按需编译、热更新等能力受到广泛关注。Vite 利用浏览器原生的 ES 模块导入功能,提供近乎即时的开发环境启动速度和高度优化的开发体验。

安装 Vite

首先确保你的系统中安装了 Node.js(建议使用 LTS 版本)。然后通过 npm 或 yarn 全局安装 Vite:

npm install -g create-vite
# Or use yarn
yarn global add create-vite

创建新项目

使用 `create-vite` 命令创建一个新的 Vite 项目。以下是创建 Vue 项目的示例:

create-vite my-vite-project --template vue
cd my-vite-project

这将初始化一个基于 Vue 3 的 Vite 项目。

开发和运行

在项目根目录下,运行以下命令启动开发服务器:

npm run dev
# Or use yarn
yarn dev

Vite 会立即启动一个本地开发服务器,你可以在浏览器中访问 `http://localhost:5173` 查看你的应用程序。Vite 支持热模块替换(HMR),这意味着当你编辑代码时,浏览器页面会实时更新,无需刷新。

构建生产版本

当您准备好部署应用程序时,运行以下命令来构建生产版本:

npm run build
# Or use yarn
yarn build

这将生成一个优化的、可用于生产的静态文件夹,通常位于“dist”目录中。

Vite 配置

// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'; // Assume we use Vue
import { resolve } from 'path';

// Environment variables
const env = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';

export default defineConfig({
// Application base path
base: '/my-app/',

// Project entry file
root: './src',

// Output directory
outDir: 'dist',

mode: env,
envPrefix: 'VITE_', // All environment variables starting with VITE_ will be injected into import.meta.env
envFile: `.env.${env}.local`, // Read the .env file for the corresponding environment

// Dynamically import polyfill
optimizeDeps: {
    include: ['@vue/reactivity'], // Force inclusion of dynamically imported libraries
},

// Server configuration
server: {
    // Server port
    port: 3000,
    // Whether to enable HTTPS
    https: false,
    // Enable hot module replacement
    hmr: true,
    // Proxy configuration for API request forwarding
    proxy: {
        '/api': {
            target: 'http://localhost:8000',
            changeOrigin: true,
        },
    },
    middlewareMode: true, // Enable middleware mode
    before(app) {
        app.use(async (ctx, next) => {
            ctx.body = 'Hello, this is a custom middleware!';
            await next();
        });
    },
},

// Build configuration
build: {
    // Whether to compress code in the production environment
    minify: true,
    // Output directory
    outDir: 'dist',
    // Resource file storage directory
    assetsDir: 'assets',
    // Chunk size warning threshold
    chunkSizeWarningLimit: 500,
    rollupOptions: {
        input: 'src/main.js',
        output: {
            manualChunks(id) {
                if (id.startsWith('node_modules')) {
                    return id.toString().replace(/(\.[a-z]+)|[\\/]/g, '_');
                }
            },
        },
    },
},

// Preprocessor configuration, such as CSS
css: {
    // CSS modularization
    modules: {
        generateScopedName: '[name]_[local]_[hash:base64:5]',
    },
},

// Preview environment configuration
preview: {
    port: 8080,
},

// Plugin configuration
plugins: [
// You can add custom or third-party plugins here
],

// Resolve options
resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
    // Alias ​​configuration
    alias: {
        '@': '/src',
    },
},

// Esbuild configuration for optimizing build speed
esbuild: {
    // Enable/disable esbuild tree shaking
    treeShaking: true,
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
},

transpileDependencies: ['my-dep'], // Specify dependencies to be translated

// Additional Rollup configuration
rollupOptions: {
// You can add Rollup configuration items here
},
});

Vite 的核心功能

  • 快速启动:Vite 利用浏览器原生的 ES 模块支持,无需捆绑即可快速启动开发服务器,显著提高启动速度。
  • 按需编译:在开发模式下,Vite 仅编译您正在查看的模块,大大加快了编辑刷新周期。
  • 热模块替换(HMR):Vite 提供非常快速的 HMR 体验,几乎无缝的实时更新。
  • 配置简单:Vite的配置文件vite.config.js相比Webpack更加简洁,降低了入门门槛。
  • 兼容性好:Vite 支持多种框架,包括 Vue、React、Preact、Svelte 等,并且可以轻松适配自定义配置。
  • 插件系统:Vite 提供了强大的插件系统,允许开发者扩展其功能以满足特定的项目需求。
  • 高级探索

  • 配置文件:虽然 Vite 的默认配置已经很强大了,但是你可以在 vite.config.js 中进行更多的自定义,比如配置代理、别名、CSS 预处理器等。
  • Vue DevTools:开发 Vue 应用程序时,请确保安装并启用 Vue DevTools 浏览器扩展,以便更好地调试应用程序状态。
  • TypeScript 支持:如果你在项目中使用 TypeScript,Vite 已经默认支持它。你只需要在项目中包含 .ts 或 .tsx 文件即可。
  • 优化:了解如何使用 Vite 内置的优化选项和外部插件进一步提高应用程序性能。