Skip to content

安装 ​

这个库需要node.js版本 >= 14

sh
npm i -D vite-ssg vue-router @unhead/vue
diff
// package.json
{
  "scripts": {
    "dev": "vite",
-   "build": "vite build"
+   "build": "vite-ssg build"

    // OR if you want to use another vite config file
+   "build": "vite-ssg build -c another-vite.config.ts"
  }
}
ts
// src/main.ts
import { ViteSSG } from 'vite-ssg'
import App from './App.vue'

// 需要用`export const creatApp`,而不是原来的`createApp(App).mount('#app')`
export const createApp = ViteSSG(
  // 根组件
  App,
  // vue-router配置
  { routes },
  // 自定义初始化的函数
  ({ app, router, routes, isClient, initialState }) => {
    // 安装其他插件…….
  },
)

如何让 Rollup 对你的客户端代码进行 tree-shaking(树摇优化) ​

为了让Rollup在构建时能够对你的客户端代码进行tree-shaking(摇树优化),你需要用import.meta.env.SSR来包裹你的代码,也就是说,检查当前构建是否是针对服务端的:这样Rollup就会把服务端代码从客户端构建中移除。

ts
if (import.meta.env.SSR) {
  // 在客户端构建,你的服务端代码将会被移除
}
else {
  // 在服务端构建,你的客户端代码将会被移除
}

单页 SSG ​

如果只需要对单个首页进行 SSG(静态站点生成)(也就是说,不使用 vue-router),那么改为导入vite-ssg/single-page,并且只需安装@unhead/vue(npm i -D vite-ssg @unhead/vue)。

ts
// src/main.ts
import { ViteSSG } from 'vite-ssg/single-page'
import App from './App.vue'

// 需要用`export const creatApp`,而不是原来的`createApp(App).mount('#app')`
export const createApp = ViteSSG(App)

<ClientOnly/> ​

ClientOnly 组件在应用创建时会被全局注册。

html
<client-only>
  <your-client-side-components />
  <template #placeholder>
    <your-placeholder-components />
  </template>
</client-only>

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