Skip to content
On this page

Vite 与框架集成

Vite 设计时就考虑了与各种前端框架的集成,提供了对主流框架的官方支持和优化配置。

Vue 集成

安装 Vue 插件

bash
npm install @vitejs/plugin-vue -D

基础配置

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
})

Vue 特性支持

javascript
// vite.config.js
import vue from '@vitejs/plugin-vue'

export default {
  plugins: [
    vue({
      // Vue 编译选项
      include: [/\.vue$/],  // 包含的文件
      exclude: [],          // 排除的文件
      
      // 模板编译选项
      template: {
        // 编译模板时的选项
        transformAssetUrls: {
          base: null,
          includeAbsolute: false
        }
      }
    })
  ]
}

Vue 3 特性

vue
<!-- Composition API 支持 -->
<template>
  <div>{{ message }}</div>
</template>

<script setup>
// &lt;script setup&gt; 语法糖支持
import { ref, onMounted } from 'vue'

const message = ref('Hello Vite + Vue!')

onMounted(() => {
  console.log('Component mounted')
})
</script>

React 集成

安装 React 插件

bash
npm install @vitejs/plugin-react -D

基础配置

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

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
})

React 特性支持

javascript
// vite.config.js
import react from '@vitejs/plugin-react'

export default {
  plugins: [
    react({
      // JSX 转换选项
      jsxRuntime: 'automatic',  // 使用自动 JSX 转换
      
      // Babel 选项
      babel: {
        presets: [],
        plugins: [
          // 添加 Babel 插件
        ]
      },
      
      // 开发选项
      fastRefresh: true  // 启用 Fast Refresh
    })
  ]
}

TypeScript 支持

json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

Preact 集成

安装 Preact 插件

bash
npm install @preact/preset-vite -D

配置

javascript
// vite.config.js
import { defineConfig } from 'vite'
import preact from '@preact/preset-vite'

export default defineConfig({
  plugins: [preact()],
  resolve: {
    alias: {
      'react': 'preact/compat',
      'react-dom': 'preact/compat'
    }
  }
})

Svelte 集成

安装 Svelte 插件

bash
npm install @sveltejs/vite-plugin-svelte -D

基础配置

javascript
// vite.config.js
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

export default defineConfig({
  plugins: [svelte()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  }
})

Svelte 配置选项

javascript
// vite.config.js
import { svelte } from '@sveltejs/vite-plugin-svelte'

export default {
  plugins: [
    svelte({
      // 编译选项
      compilerOptions: {
        dev: !isProduction,
        hydratable: true
      },
      
      // 预处理器选项
      preprocess: [
        // 使用 svelte-preprocess 等
      ],
      
      // 调试选项
      onwarn: (warning, defaultHandler) => {
        // 警告处理
      }
    })
  ]
}

Lit 集成

安装 Lit 插件

bash
npm install @lit-labs/vite-plugin -D

配置

javascript
// vite.config.js
import { defineConfig } from 'vite'
import lit from '@lit-labs/vite-plugin'

export default defineConfig({
  plugins: [lit()],
  build: {
    target: 'es2020'  // Lit 需要较新的 ES 特性
  }
})

Angular 集成

虽然 Angular 有自己官方的 CLI,但也可以使用 Vite:

bash
npm install vite-plugin-angular -D
javascript
// vite.config.js
import { defineConfig } from 'vite'
import angular from 'vite-plugin-angular'

export default defineConfig({
  plugins: [angular()],
  build: {
    rollupOptions: {
      external: ['@angular/core']
    }
  }
})

框架无关的 Web Components

基础配置

javascript
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, 'src/my-element.js'),
      name: 'MyElement',
      formats: ['es', 'umd'],
      fileName: (format) => `my-element.${format}.js`
    },
    rollupOptions: {
      external: [],
      output: {
        globals: {}
      }
    }
  }
})

自定义元素示例

javascript
// my-element.js
export class MyElement extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
  }

  connectedCallback() {
    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: block;
        }
      </style>
      <h1>Hello from Web Component!</h1>
    `
  }
}

customElements.define('my-element', MyElement)

框架特定优化

Vue 优化

javascript
// vite.config.js
import vue from '@vitejs/plugin-vue'

export default {
  plugins: [
    vue({
      // 启用模板编译优化
      template: {
        compilerOptions: {
          // 可以在这里配置模板编译选项
        }
      }
    })
  ],
  build: {
    rollupOptions: {
      external: ['vue'],
      output: {
        globals: {
          vue: 'Vue'
        }
      }
    }
  }
}

React 优化

javascript
// vite.config.js
import react from '@vitejs/plugin-react'

export default {
  plugins: [
    react({
      // 优化 Fast Refresh
      jsxImportSource: 'react'
    })
  ],
  define: {
    // React 需要的全局定义
    '__REACT_DEVTOOLS_GLOBAL_HOOK__': 'null'
  }
}

多框架支持

同时支持多个框架

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

export default defineConfig({
  plugins: [
    // 根据文件扩展名使用不同插件
    vue({
      include: [/\.vue$/, /\.vue\?vue/]
    }),
    react({
      include: [/\.jsx$/, /\.tsx$/]
    })
  ],
  resolve: {
    conditions: ['development', 'browser']
  }
})

服务端渲染 (SSR)

Vue SSR 配置

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

export default defineConfig({
  plugins: [vue()],
  build: {
    ssr: true,  // 启用 SSR 构建
    outDir: 'dist/server'
  }
})

React SSR 配置

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

export default defineConfig({
  plugins: [react()],
  build: {
    ssr: 'src/entry-server.jsx',  // SSR 入口
    outDir: 'dist/server'
  }
})

框架特定插件

VueUse 集成

javascript
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    vue(),
    VitePWA({
      // PWA 配置
      registerType: 'autoUpdate',
      manifest: {
        name: 'My App',
        short_name: 'MyApp',
        theme_color: '#ffffff'
      }
    })
  ]
})

组件库开发

javascript
// vite.config.js - 组件库构建
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, 'src/index.js'),
      name: 'MyComponentLibrary',
      fileName: (format) => `my-lib.${format}.js`
    },
    rollupOptions: {
      external: ['vue'],  // 或 ['react', 'react-dom']
      output: {
        globals: {
          vue: 'Vue',
          react: 'React'
        }
      }
    }
  }
})

迁移指南

从其他构建工具迁移

javascript
// webpack.config.js -> vite.config.js 转换示例
// 之前 (webpack)
module.exports = {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  module: {
    rules: [
      // ...
    ]
  }
}

// 之后 (vite)
import { defineConfig } from 'vite'

export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
  // 大部分配置由 Vite 自动处理
})

通过这些集成方式,Vite 可以很好地支持各种前端框架,提供快速的开发体验和优化的构建输出。