• Stars
    star
    1,198
  • Rank 39,074 (Top 0.8 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Static site generation for Vue 3 on Vite

Vite SSG

Static-site generation for Vue 3 on Vite.

NPM version

ℹ️ Vite 2 is supported from v0.2.x, Vite 1's support is discontinued.

Install

This library requires Node.js version >= 14

npm i -D vite-ssg vue-router @vueuse/head
// 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"
  }
}
// src/main.ts
import { ViteSSG } from 'vite-ssg'
import App from './App.vue'

// `export const createApp` is required instead of the original `createApp(App).mount('#app')`
export const createApp = ViteSSG(
  // the root component
  App,
  // vue-router options
  { routes },
  // function to have custom setups
  ({ app, router, routes, isClient, initialState }) => {
    // install plugins etc.
  },
)

Single Page SSG

For SSG of an index page only (i.e. without vue-router); import vite-ssg/single-page instead, and only install @vueuse/head (npm i -D vite-ssg @vueuse/head).

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

// `export const createApp` is required instead of the original `createApp(App).mount('#app')`
export const createApp = ViteSSG(App)

<ClientOnly/>

The ClientOnly component is registered globally when the app is created.

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

Document head

From v0.4.0 onwards, we ship @vueuse/head to manage the document-head out of the box. You can use it directly in your pages/components. For example:

<template>
  <button @click="count++">Click</button>
</template>

<script setup>
import { useHead } from '@vueuse/head'

useHead({
  title: 'Website Title',
  meta: [
    {
      name: 'description',
      content: 'Website description',
    },
  ],
})
</script>

That's all! No configuration is needed. Vite SSG will automatically handle the server-side rendering and merging.

See @vueuse/head's docs for more usage information about useHead.

Critical CSS

Vite SSG has built-in support for generating Critical CSS inlined in the HTML via the critters package. Install it with:

npm i -D critters

Critical CSS generation will automatically be enabled for you.

To configure critters, pass its options into ssgOptions.crittersOptions in vite.config.ts:

// vite.config.ts
export default defineConfig({
  ssgOptions: {
    crittersOptions: {
      // E.g., change the preload strategy
      preload: 'media',
      // Other options: https://github.com/GoogleChromeLabs/critters#usage
    },
  },
})

Initial State

The initial state comprises data that is serialized with your server-side generated HTML and is hydrated in the browser when accessed. This data can be data fetched from a CDN, an API, etc, and is typically needed as soon as the application starts or is accessed for the first time.

The main advantage of setting the application's initial state is that the statically generated pages do not need to refetch the data as it is fetched and serialized into the page's HTML at build time.

The initial state is a plain JavaScript object that can be set during SSR. I.e. when statically generating the pages like this:

// src/main.ts

// ...

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

    if (import.meta.env.SSR) {
      // Set initial state during server side
      initialState.data = { cats: 2, dogs: 3 }
    }
    else {
      // Restore or read the initial state on the client side in the browser
      console.log(initialState.data) // => { cats: 2, dogs: 3 }
    }

    // ...
  },
)

Typically, you will use this with an application store, such as Vuex or Pinia. See below for examples:

When using Pinia

Following Pinia's guide, you will to adapt your main.{ts,js} file to look like this:

// main.ts
import { ViteSSG } from 'vite-ssg'
import { createPinia } from 'pinia'
import routes from 'virtual:generated-pages'
// use any store you configured that you need data from on start-up
import { useRootStore } from './store/root'
import App from './App.vue'

export const createApp = ViteSSG(
  App,
  { routes },
  ({ app, router, initialState }) => {
    const pinia = createPinia()
    app.use(pinia)

    if (import.meta.env.SSR)
      initialState.pinia = pinia.state.value
    else
      pinia.state.value = initialState.pinia || {}

    router.beforeEach((to, from, next) => {
      const store = useRootStore(pinia)
      if (!store.ready)
        // perform the (user-implemented) store action to fill the store's state
        store.initialize()
      next()
    })
  },
)
When using Vuex

// main.ts
import { ViteSSG } from 'vite-ssg'
import routes from 'virtual:generated-pages'
import { createStore } from 'vuex'
import App from './App.vue'

// Normally, you should definitely put this in a separate file
// in order to be able to use it everywhere
const store = createStore({
  // ...
})

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

    if (import.meta.env.SSR)
      initialState.store = store.state
    else
      store.replaceState(initialState.store)

    router.beforeEach((to, from, next) => {
      // perform the (user-implemented) store action to fill the store's state
      if (!store.getters.ready)
        store.dispatch('initialize')

      next()
    })
  },
)

For an example on how to use a store with an initial state in a single page app, see the single page example.

State Serialization

By default, the state is deserialized and serialized by using JSON.stringify and JSON.parse respectively. If this approach works for you, you should definitely stick to it as it yields far better performance.

You may use the transformState option in the ViteSSGClientOptions options object as shown below. A valid approach besides JSON.stringify and JSON.parse is @nuxt/devalue (which is used by Nuxt.js):

import devalue from '@nuxt/devalue'
import { ViteSSG } from 'vite-ssg'
// ...
import App from './App.vue'

export const createApp = ViteSSG(
  App,
  { routes },
  ({ app, router, initialState }) => {
    // ...
  },
  {
    transformState(state) {
      return import.meta.env.SSR ? devalue(state) : state
    },
  },
)

A minor remark when using @nuxt/devalue: In case, you are getting an error because of a require within the package @nuxt/devalue, you have to add the following piece of config to your Vite config:

// vite.config.ts
// ...

export default defineConfig({
  resolve: {
    alias: {
      '@nuxt/devalue': '@nuxt/devalue/dist/devalue.js',
    },
  },
  // ...
})

Async Components

Some applications may make use of Vue features that cause components to render asynchronously (e.g. suspense). When these features are used in ways that can influence initialState, the onSSRAppRendered may be used in order to ensure that all async operations are complete during the initial application render. For example:

const { app, router, initialState, isClient, onSSRAppRendered } = ctx

const pinia = createPinia()
app.use(pinia)

if (isClient) {
  pinia.state.value = (initialState.pinia) || {}
}
else {
  onSSRAppRendered(() => {
    initialState.pinia = pinia.state.value
  })
}

Configuration

You can pass options to Vite SSG in the ssgOptions field of your vite.config.js

// vite.config.js

export default {
  plugins: [],
  ssgOptions: {
    script: 'async',
  },
}

See src/types.ts. for more options available.

Custom Routes to Render

You can use the includedRoutes hook to include or exclude route paths to render, or even provide some completely custom ones.

// vite.config.js

export default {
  plugins: [],
  ssgOptions: {
    includedRoutes(paths, routes) {
      // exclude all the route paths that contains 'foo'
      return paths.filter(i => !i.includes('foo'))
    },
  },
}
// vite.config.js

export default {
  plugins: [],
  ssgOptions: {
    includedRoutes(paths, routes) {
      // use original route records
      return routes.flatMap((route) => {
        return route.name === 'Blog'
          ? myBlogSlugs.map(slug => `/blog/${slug}`)
          : route.path
      })
    },
  },
}

Alternatively, you may export the includedRoutes hook from your server entry file. This will be necessary if fetching your routes requires the use of environment variables managed by Vite.

// main.ts

import { ViteSSG } from 'vite-ssg'
import App from './App.vue'

export const createApp = ViteSSG(
  App,
  { routes },
  ({ app, router, initialState }) => {
    // ...
  },
)
export async function includedRoutes(paths, routes) {
  // Sensitive key is managed by Vite - this would not be available inside
  // vite.config.js as it runs before the environment has been populated.
  const apiClient = new MyApiClient(import.meta.env.MY_API_KEY)

  return Promise.all(
    routes.flatMap(async (route) => {
      return route.name === 'Blog'
        ? (await apiClient.fetchBlogSlugs()).map(slug => `/blog/${slug}`)
        : route.path
    }),
  )
}

Comparison

Use Vitepress when you want:

  • Zero config, out of the box SSG
  • A single-purpose documentation site
  • Lightweight (No double payload)

Use Vite SSG when you want:

  • More control on the build process and tooling
  • The flexible plugin system
  • Multi-purpose application with some SSG to improve SEO and loading speed

Cons:

  • Double payload

Example

See Vitesse.

Thanks to the prior work

Contribution

Please refer to https://github.com/antfu/contribute.

License

MIT License Β© 2020-PRESENT Anthony Fu

More Repositories

1

vitesse

πŸ• Opinionated Vite + Vue Starter Template
TypeScript
8,522
star
2

ni

πŸ’‘ Use the right package manager
TypeScript
4,527
star
3

icones

⚑️ Icon Explorer with Instant searching, powered by Iconify
Vue
4,525
star
4

unplugin-vue-components

πŸ“² On-demand components auto importing for Vue
TypeScript
3,011
star
5

unocss

The instant on-demand atomic CSS engine.
TypeScript
2,990
star
6

unplugin-icons

🀹 Access thousands of icons as components on-demand universally.
TypeScript
2,793
star
7

vitesse-webext

⚑️ WebExtension Vite Starter Template
TypeScript
2,581
star
8

unplugin-auto-import

Auto import APIs on-demand for Vite, Webpack and Rollup
TypeScript
2,307
star
9

vscode-file-nesting-config

Config of File Nesting for VS Code
JavaScript
2,132
star
10

vue-starport

πŸ›° Shared component across routes with animations
TypeScript
1,744
star
11

vscode-settings

My VS Code settings and extensions
1,739
star
12

eslint-config

Anthony's ESLint config presets
JavaScript
1,605
star
13

vitesse-nuxt3

Vitesse for Nuxt 3 πŸ”πŸ’šβš‘οΈ
TypeScript
1,510
star
14

shikiji

A syntax highlighter based on TextMate grammars. ESM rewrite of shiki, with more features and capabilities.
TypeScript
1,465
star
15

reactivue

πŸ™Š Use Vue Composition API in React components
TypeScript
1,415
star
16

taze

πŸ₯¦ A modern cli tool that keeps your deps fresh
TypeScript
1,233
star
17

handle

A Chinese Hanzi variation of Wordle - 汉字 Wordle
TypeScript
1,194
star
18

qrcode-toolkit

Anthony's QR Code Toolkit for AI generated QR Codes
Vue
1,111
star
19

case-police

🚨 Make the case correct, PLEASE!
TypeScript
1,098
star
20

vite-plugin-inspect

Inspect the intermediate state of Vite plugins
Vue
1,009
star
21

use

Things I am using
991
star
22

vitesse-lite

⛺️ Lightweight version of Vitesse
TypeScript
901
star
23

drauu

Headless SVG-based drawboard in browser.
TypeScript
817
star
24

broz

A simple, frameless browser for screenshots
JavaScript
745
star
25

iroiro

Beautiful Colors Lookup in CLI
TypeScript
735
star
26

retypewriter

Replay the steps of your changes at ease.
TypeScript
715
star
27

live-draw

A tool allows you to draw on screen real-time.
C#
706
star
28

sd-webui-qrcode-toolkit

Anthony's QR Toolkit for Stable Diffusion WebUI
JavaScript
640
star
29

changelogithub

Generate changelog for GitHub
TypeScript
613
star
30

vite-plugin-md

Markdown with Vue for Vite
TypeScript
602
star
31

vscode-smart-clicks

Smart selection with double clicks for VS Code.
TypeScript
601
star
32

unplugin-vue2-script-setup

πŸ’‘ Bring `<script setup>` to Vue 2.
TypeScript
567
star
33

sponsorkit

πŸ’– Toolkit for generating sponsors images πŸ˜„
TypeScript
550
star
34

eslint-flat-config-viewer

A visual tool to help you view and understand your ESLint Flat config.
Vue
549
star
35

unconfig

A universal solution for loading configurations.
TypeScript
524
star
36

utils

Collection of common JavaScript / TypeScript utils
TypeScript
493
star
37

100

My 100-day project of exploring design, compform, and new things.
Vue
491
star
38

v-lazy-show

Compile-time directive to lazy initialize v-show for Vue
TypeScript
487
star
39

antfu.me

My personal website
Markdown
463
star
40

raycast-multi-translate

A Raycast extension that translates text to multiple languages at once
TypeScript
454
star
41

vue-reuse-template

Define and reuse Vue template inside the component scope.
TypeScript
440
star
42

vite-node

Vite as Node.js runtime
JavaScript
428
star
43

vscode-browse-lite

πŸš€ An embedded browser in VS Code
TypeScript
425
star
44

vscode-vite

One step faster for Vite in VS Code ⚑️
TypeScript
404
star
45

vscode-theme-vitesse

πŸ• Vitesse theme for VS Code
TypeScript
395
star
46

starter-ts

Starter template for TypeScript library
TypeScript
386
star
47

vue-template-promise

Template as Promise in Vue
TypeScript
373
star
48

vue-global-api

Use Vue Composition API globally
TypeScript
331
star
49

vue-router-better-scroller

Enhanced scroll behavior for Vue Router
TypeScript
327
star
50

qr-scanner-wechat

QR Code scanner in JS with Open CV and WeChat's Algorithm
JavaScript
322
star
51

starter-vscode

Starter template for VS Code Extension
TypeScript
299
star
52

vscode-iconify

πŸ™‚ Iconify IntelliSense for VS Code
TypeScript
294
star
53

1990-script

Make your GitHub history back to 1990
Shell
293
star
54

p

Toolkit for managing multiple promises
TypeScript
284
star
55

wenyan-lang-vscode

文言 Wenyan Lang for VS Code
TypeScript
277
star
56

pnpm-patch-i

A better and interactive pnpm patch
TypeScript
265
star
57

fsxx

File system in zx style
JavaScript
262
star
58

birpc

Message-based two-way remote procedure call.
TypeScript
245
star
59

vue-minesweeper

A tiny minesweeper clone in Vue 3
TypeScript
242
star
60

contribute

Contribution guide for my projects
231
star
61

purge-icons

🎐 Bundles icons on demand
TypeScript
229
star
62

vscode-open-in-github-button

Add a button to go to the GitHub on the status bar.
TypeScript
224
star
63

github-doorcat

😼 Supercharges GitHub navbar for fast navigation [WIP]
TypeScript
214
star
64

vscode-goto-alias

Go to Definition following alias redirections.
TypeScript
211
star
65

refined-github-notifications

UserScript that enhances the GitHub Notifications
JavaScript
208
star
66

eslint-plugin-command

Comment-as-command for one-off codemod with ESLint.
TypeScript
195
star
67

nuxt-server-fn

Server functions in client for Nuxt 3
TypeScript
194
star
68

magic-string-stack

magic-string with the capability of committing changes.
TypeScript
190
star
69

vscode-array-index-inlay

Show array index inlay hints for large arrays for VS Code
TypeScript
185
star
70

eslint-typegen

Generate types from ESLint rule schemas, with auto-completion and type-checking for rule options.
TypeScript
185
star
71

prism-theme-vars

A customizable Prism.js theme using CSS variables
CSS
178
star
72

what-time

What time works for you?
Vue
177
star
73

esbuild-node-loader

Transpile TypeScript to ESM with Node.js loader.
JavaScript
175
star
74

userscript-clean-twitter

Bring back the peace on Twitter
JavaScript
174
star
75

vitesse-nuxt-bridge

πŸ• Vitesse experience for Nuxt 2 and Vue 2
Vue
174
star
76

vscode-icons-carbon

Carbon Visual Studio Code product icon theme
TypeScript
170
star
77

talks

Slides & code for my talks
Vue
170
star
78

fs-spy

Monitoring fs accessing for Node process
TypeScript
166
star
79

vite-plugin-glob

The design experiment for import.meta.glob from Vite.
TypeScript
164
star
80

diff-match-patch-es

ESM and TypeScript rewrite of Google's diff-match-patch for JavaScript
TypeScript
159
star
81

vite-plugin-optimize-persist

Persist dynamically analyzed dependencies optimization
TypeScript
155
star
82

eslint-ts-patch

Support loading eslint.config.mjs and eslint.config.ts as flat config files for ESLint.
JavaScript
155
star
83

markdown-it-github-alerts

Support GitHub-style alerts for markdown-it
TypeScript
153
star
84

regex-doctor

Monitor your RegExp consumption and provide suggestions to improve performance.
TypeScript
152
star
85

v-dollar

jQuery-like Vue Reactivity API
TypeScript
146
star
86

.github

The default community health files for all my repos on GitHub
146
star
87

p5i

p5.js, but with more friendly instance mode APIs
TypeScript
139
star
88

vscode-pnpm-catalog-lens

Show versions inline for PNPM catalog: field
TypeScript
136
star
89

magic-string-extra

Extended magic-string with extra utilities
TypeScript
131
star
90

export-size

Analysis bundle cost for each export of a package
TypeScript
130
star
91

eslint-plugin-format

Format various languages with formatters in ESLint
TypeScript
129
star
92

local-pkg

Get information on local packages.
TypeScript
126
star
93

vite-plugin-restart

Custom files/globs to restart Vite server
TypeScript
124
star
94

pkg-exports

Get exports of an local npm package.
TypeScript
118
star
95

qr-verify

A CLI to verify scannable QR Code in batch
TypeScript
114
star
96

eslint-plugin-antfu

Anthony extended ESLint rules.
TypeScript
114
star
97

install-pkg

Install package programmatically.
TypeScript
114
star
98

deploy-check

WIP, Prevent runtime errors earlier in CI
TypeScript
113
star
99

fast-npm-meta

A lightweight API server to get npm package metadata, resolve the latest versions on server, and batch multiple package resolutions in one request.
TypeScript
110
star
100

markdown-it-mdc

MDC (Markdown Components) syntax for markdown-it.
TypeScript
106
star