vue SSG实现
Vue SSG 实现方法
Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是一些常见的方法和步骤:
使用 Nuxt.js
Nuxt.js 是一个基于 Vue 的框架,内置了 SSG 支持。通过简单的配置即可生成静态站点。
安装 Nuxt.js:
npx create-nuxt-app my-ssg-project
在 nuxt.config.js 中配置 target 为 static:
export default {
target: 'static'
}
运行生成命令:
npm run generate
生成的静态文件会保存在 dist 目录中,可以直接部署到任何静态托管服务。
使用 VitePress
VitePress 是一个基于 Vite 和 Vue 的静态站点生成器,适合文档类站点。
安装 VitePress:
npm install -D vitepress
创建配置文件 .vitepress/config.js:
module.exports = {
title: 'My SSG Site',
description: 'A static site generated with VitePress'
}
运行开发服务器:
npx vitepress dev
生成静态文件:
npx vitepress build
使用 VuePress
VuePress 是另一个流行的 Vue 静态站点生成器,适合文档和博客。
安装 VuePress:
npm install -D vuepress
创建配置文件 .vuepress/config.js:
module.exports = {
title: 'My SSG Site',
description: 'A static site generated with VuePress'
}
运行生成命令:
npx vuepress build
手动配置 Vue 项目实现 SSG
对于自定义需求,可以手动配置 Vue 项目实现 SSG。
安装 @vue/server-renderer:
npm install @vue/server-renderer
创建服务端入口文件 src/entry-server.js:
import { renderToString } from '@vue/server-renderer'
import { createApp } from './main'
export async function render(url, manifest) {
const { app, router } = createApp()
await router.push(url)
await router.isReady()
const ctx = {}
const html = await renderToString(app, ctx)
return [html, ctx]
}
创建生成脚本 scripts/generate.js:
const fs = require('fs')
const path = require('path')
const { render } = require('../src/entry-server')
const routes = ['/', '/about', '/contact']
async function generate() {
for (const route of routes) {
const [html] = await render(route)
const fileName = route === '/' ? 'index.html' : `${route.slice(1)}.html`
const filePath = path.join(__dirname, '../dist', fileName)
fs.mkdirSync(path.dirname(filePath), { recursive: true })
fs.writeFileSync(filePath, html)
}
}
generate()
运行生成命令:
node scripts/generate.js
部署生成的静态站点
生成的静态文件可以部署到各种托管服务:

- Netlify
- Vercel
- GitHub Pages
- AWS S3
- 任何支持静态文件的服务器
每种方法都有其优势和适用场景,Nuxt.js 和 VuePress 提供了更多开箱即用的功能,而手动配置则提供了更大的灵活性。






