当前位置:首页 > VUE

vue SSG实现

2026-03-07 01:37:01VUE

Vue SSG 实现方法

Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是一些常见的方法和步骤:

使用 Nuxt.js

Nuxt.js 是一个基于 Vue 的框架,内置了 SSG 支持。通过简单的配置即可生成静态站点。

安装 Nuxt.js:

npx create-nuxt-app my-ssg-project

nuxt.config.js 中配置 targetstatic

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'
}

运行开发服务器:

vue SSG实现

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'
}

运行生成命令:

vue SSG实现

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 提供了更多开箱即用的功能,而手动配置则提供了更大的灵活性。

标签: vueSSG
分享给朋友:

相关文章

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组件中引入…

vue datepicker 实现

vue datepicker 实现

实现 Vue Datepicker 的基本方法 在 Vue 项目中实现日期选择功能,可以使用第三方库如 vue-datepicker 或 v-calendar。以下是两种常见实现方式: 安装 vue…

vue SSG实现

vue SSG实现

Vue SSG 实现方法 Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是几种常见的方法: 使用 VuePress VuePress 是一个基于 Vue 的静态站点生成器,适合文档…

vue实现erp

vue实现erp

Vue实现ERP系统的关键步骤 技术选型与架构设计 采用Vue 3 + TypeScript构建前端,搭配Pinia状态管理,Element Plus或Ant Design Vue作为UI框架。后端可…

vue实现picker

vue实现picker

Vue 实现 Picker 组件的方法 在 Vue 中实现 Picker 组件可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 HTML 和 CSS 实现 通过 Vue 的模板和样式绑定,…

vue实现布局

vue实现布局

Vue 实现布局方法 Vue 提供了多种方式实现页面布局,可以通过组件化、CSS 框架或自定义样式完成。以下是几种常见方法: 使用 CSS Flexbox 或 Grid 通过 Vue 单文件组件结合…