Vite 与模块联邦进阶实战

Vite 启动快是因为用了原生 ESM,但生产构建呢?模块联邦怎么让两个独立部署的应用共享组件?本文从 Vite 配置优化到模块联邦实战,讲清前端构建工具的进阶用法。

Vite 与模块联邦配图:蓝色渐变背景上闪电底座连接模块方块与节点网络,扁平科技插画
Vite + Module Federation:极速构建与跨应用共享

一、Vite 为什么快

Webpack 启动要打包整个项目,Vite 利用浏览器原生 ESM,开发服务器启动时不打包,浏览器请求哪个文件才编译哪个。大型项目从几分钟启动降到几百毫秒。

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
  },
  build: {
    // 分包优化
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
        },
      },
    },
    // 产物压缩目标
    target: 'es2015',
  },
})
HMR 原理:Vite 的热模块替换基于 ESM,修改文件后只重新编译那个模块并通知浏览器替换,不需要刷新整个页面。比 Webpack 的 HMR 更快更稳定。

二、构建产物优化

// 分析打包体积
// 安装:npm install -D rollup-plugin-visualizer
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
  plugins: [
    visualizer({ open: true, gzipSize: true }),
  ],
  build: {
    // 单文件大小警告阈值
    chunkSizeWarningLimit: 500,
    // CSS 代码分割
    cssCodeSplit: true,
    // 资源内联阈值(KB)
    assetsInlineLimit: 4096,
  },
})

用 visualizer 看打包产物的组成,找出体积大的依赖,针对性做分包或替换。

三、环境变量与多环境

# .env.development
VITE_API_BASE=http://localhost:8080

# .env.production
VITE_API_BASE=https://api.example.com

# 在代码中使用
const apiBase = import.meta.env.VITE_API_BASE
console.log(apiBase)

四、模块联邦是什么

模块联邦(Module Federation)允许一个应用直接运行另一个应用暴露的模块,两个应用独立部署、独立开发,运行时动态加载共享代码。

// 应用 A 的 vite.config.js(作为 Host)
import { defineConfig } from 'vite'
import { federation } from '@originjs/vite-plugin-federation'

export default defineConfig({
  plugins: [
    federation({
      name: 'host-app',
      remotes: {
        remoteApp: 'http://localhost:3001/assets/remoteEntry.js',
      },
      shared: ['react', 'react-dom'],
    }),
  ],
})

// 在应用 A 中直接使用应用 B 的组件
import RemoteButton from 'remoteApp/Button'

function App() {
  return <RemoteButton label="来自远程的按钮" />
}

五、远程应用配置

// 应用 B 的 vite.config.js(作为 Remote)
import { defineConfig } from 'vite'
import { federation } from '@originjs/vite-plugin-federation'

export default defineConfig({
  plugins: [
    federation({
      name: 'remote-app',
      filename: 'remoteEntry.js',
      exposes: {
        './Button': './src/components/Button.jsx',
        './Card': './src/components/Card.jsx',
      },
      shared: ['react', 'react-dom'],
    }),
  ],
  build: {
    target: 'esnext',  // 模块联邦需要现代浏览器支持
  },
})

六、微前端场景

模块联邦是微前端架构的核心技术之一。主应用(Host)负责布局和路由,子应用(Remote)负责各自的业务页面。每个子应用独立部署,主应用运行时动态加载。

方案共享代码部署独立适用场景
npm 包是否(版本锁定)稳定的共享组件库
模块联邦是是微前端、多团队协作
iframe否是简单隔离

七、总结

Vite 是现代前端开发的标配构建工具,启动快、HMR 稳定、配置简单。模块联邦让多应用共享代码变成运行时动态加载,是微前端架构的关键技术。记住:开发用 Vite Dev Server,生产构建做分包优化,多应用共享用模块联邦。