vite-ssg使用与踩坑

5,477 阅读1分钟

Vite-SSG 介绍

Vite-SSG antfu 基于 ViteVue3 开源的一个静态站点生成器, 类似的产品有 Vuepresshexo

食用

需要 node>=14!!

npm i -D vite-ssg vue-router @vueuse/head

配置 package.json

```
// package.json
{
  "scripts": {
    "dev": "vite",
    "build": "vite-ssg build"

    // OR if you want to use another vite config file
    "build": "vite-ssg build -c another-vite.config.ts"
  }
}
```

main.ts引入

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

// 自己定义的路由配置
import routes from '@/router/index.ts'

export const createApp = ViteSSG(
  App,
  { routes },
  ({ app, router, routes, isClient, initialState }) => {

  },
)
```

路由配置的坑

Vite-SSG 路由只需要定义 routes即可, 不要使用 createRouter创建了路由!! 否则会出现以下报错, 出现 location is no defined 也是类似的原因.

image.png


错误的路由定义:

    // src/router/index.ts
    import { createWebHistory, createRouter, RouteRecordRaw } from 'vue-router'

    import Home from '@/views/Home/index.vue'

    const routes: RouteRecordRaw[] = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home,
        name: 'Home',
      }
      ...

    ]
    const router = createRouter({
      history: createWebHistory(),
      routes
    })

export default routes

正确的定义

// src/router/index.ts
import { RouteRecordRaw } from 'vue-router'

import Home from '@/views/Home/index.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    name: 'Home',
  }
  ...

]

// 不用创建
// const router = createRouter({
//   history: createWebHistory(),
//   routes
// })

export default routes


配套方案推荐

  • vite-plugin-pages 基于文件系统的路由
  • vitesse 一个简单的 Vite-SSG 模板
  • vite-plugin-pwa - PWA

更多使用方式请参考Vite-SSG官方文档