vue SSG实现
Vue SSG 实现方法
Vue 的静态站点生成(SSG)可以通过多种方式实现,以下是几种常见的方法:
使用 Nuxt.js
Nuxt.js 是一个基于 Vue 的框架,内置了 SSG 功能。通过配置 nuxt.config.js 文件,可以轻松生成静态站点。
安装 Nuxt.js:
npx create-nuxt-app my-project
配置为 SSG 模式:
在 nuxt.config.js 中设置 target: 'static':
export default {
target: 'static'
}
生成静态文件:
npm run generate
使用 VuePress
VuePress 是一个基于 Vue 的静态站点生成器,适合文档类网站。
安装 VuePress:
npm install -D vuepress
创建基本结构:
在项目根目录下创建 docs 文件夹,并添加 README.md 文件。
启动开发服务器:
npx vuepress dev docs
生成静态文件:
npx vuepress build docs
使用 Vite + Vue 3
Vite 是一个现代前端构建工具,结合 Vue 3 可以实现 SSG。
安装依赖:
npm create vite@latest my-project --template vue
添加 vite-plugin-ssr 插件:
npm install vite-plugin-ssr
配置 vite.config.js:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import ssr from 'vite-plugin-ssr/plugin'
export default defineConfig({
plugins: [vue(), ssr()]
})
生成静态文件:
npm run build
自定义 SSG 实现
对于更灵活的方案,可以手动实现 SSG。
安装依赖:
npm install vue-server-renderer vue
创建渲染脚本:
const fs = require('fs')
const Vue = require('vue')
const renderer = require('vue-server-renderer').createRenderer()
const app = new Vue({
template: '<div>Hello SSG</div>'
})
renderer.renderToString(app, (err, html) => {
if (err) throw err
fs.writeFileSync('dist/index.html', html)
})
运行脚本:
node render.js
注意事项
- 动态内容处理:SSG 生成的静态文件无法处理动态内容,需结合客户端 JavaScript 或 API 调用。
- 路由配置:确保路由与生成的静态文件匹配,避免 404 错误。
- 数据预取:在生成阶段预取数据,确保页面内容完整。
以上方法可根据项目需求选择,Nuxt.js 和 VuePress 更适合快速启动,Vite 和自定义方案提供更多灵活性。







