Skip to content

配置 ​

你可以通过 vite.config.js 中的 ssgOptions 字段向 Vite SSG 传递选项。

js
// vite.config.js

export default {
  plugins: [],
  ssgOptions: {
    script: 'async',
  },
}

查看 src/types.ts 以了解更多可用选项

自定义要渲染的路由 ​

你可以使用 includedRoutes 钩子来包含或排除要渲染的路由路径,甚至可以提供一些完全自定义的路由路径

js
// vite.config.js

export default {
  plugins: [],
  ssgOptions: {
    includedRoutes(paths, routes) {
      // 排除所有包含 'foo' 的路由路径
      return paths.filter(i => !i.includes('foo'))
    },
  },
}
js
// vite.config.js

export default {
  plugins: [],
  ssgOptions: {
    includedRoutes(paths, routes) {
      // 使用原始路由记录
      return routes.flatMap((route) => {
        return route.name === 'Blog'
          ? myBlogSlugs.map(slug => `/blog/${slug}`)
          : route.path
      })
    },
  },
}

或者,你可以从服务端入口文件中导出 includedRoutes 钩子。如果获取路由需要使用由 Vite 管理的环境变量,那么这样做是必要的。

ts
// main.ts

import { ViteSSG } from 'vite-ssg'
import App from './App.vue'

export const createApp = ViteSSG(
  App,
  { routes },
  ({ app, router, initialState }) => {
    // ...
  },
)
export async function includedRoutes(paths, routes) {
  // 敏感字串由 Vite 管理——它在 vite.config.js 内部不可用,因为该文件在环境变量填充之前就已运行。
  const apiClient = new MyApiClient(import.meta.env.MY_API_KEY)

  return Promise.all(
    routes.flatMap(async (route) => {
      return route.name === 'Blog'
        ? (await apiClient.fetchBlogSlugs()).map(slug => `/blog/${slug}`)
        : route.path
    }),
  )
}

vite-ssg 中文文档,基于 VitePress 构建