全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-23 5 分钟 ✍️ juanwangdev

vite-plugin-ssg 使用

vite-plugin-ssg 插件为 Vite 项目添加 SSG 功能。

安装插件

Bash
npm add -D vite-plugin-ssg

基础配置

JavaScript
import ssg from 'vite-plugin-ssg'

export default defineConfig({
  plugins: [ssg()]
})

构建命令

Bash
# 执行 SSG 构建
vite build
# 或
npm run build

预渲染路由配置

JavaScript
import ssg from 'vite-plugin-ssg'

export default defineConfig({
  plugins: [
    ssg({
      // 预渲染的路由列表
      routes: [
        '/',
        '/about',
        '/blog',
        '/blog/post-1',
        '/blog/post-2'
      ]
    })
  ]
})

动态路由生成

JavaScript
import ssg from 'vite-plugin-ssg'

export default defineConfig({
  plugins: [
    ssg({
      // 函数形式动态生成路由
      async getRoutes() {
        const posts = await fetchPosts()
        return [
          '/',
          '/about',
          ...posts.map(p => `/blog/${p.slug}`)
        ]
      }
    })
  ]
})

注意:动态路由需手动配置或通过 API 获取路由列表。

配置选项

选项说明
routes预渲染路由列表
getRoutes动态获取路由函数
include包含的路由匹配
exclude排除的路由匹配

构建输出

JavaScript
dist/
├── index.html
├── about/
│   └── index.html
├── blog/
│   ├── index.html
│   ├── post-1/
│   │   └── index.html
│   └── post-2/
│       └── index.html
└── assets/

与框架集成

text
import vue from '@vitejs/plugin-vue'
import ssg from 'vite-plugin-ssg'

export default defineConfig({
  plugins: [vue(), ssg()]
})

要点总结

  • vite-plugin-ssg 添加 SSG 功能
  • routes 配置预渲染路由
  • getRoutes 动态获取路由列表
  • 构建生成静态 HTML 文件

📝 发现内容有误?点击此处直接编辑

← 上一篇 SSG 概念与适用场景
下一篇 → Rollup 钩子兼容性
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库