npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@vuetify/vite-ssg

v0.21.0

Published

Server-side generation for Vite

Downloads

8

Readme

Vite SSG

Server-side 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

// package.json
{
  "scripts": {
    "dev": "vite",
-   "build": "vite build"
+   "build": "vite-ssg build"
  }
}
// src/main.ts
import { ViteSSG } from 'vite-ssg'
import App from './App.vue'

// `export const createApp` is required
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

To have SSG for the index page only (without vue-router), import from vite-ssg/single-page instead.

import { ViteSSG } from 'vite-ssg/single-page'

export const createApp = ViteSSG(App)

<ClientOnly/>

Component ClientOnly is registered globally along with the app creation.

<client-only>
  <your-client-side-components />
</client-only>

Document head

From v0.4.0, we ship @vueuse/head to manage the document head out-of-box. You can directly use it 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 handle the server-side rendering and merging automatically.

Refer to @vueuse/head's docs for more usage about useHead.

Critical CSS

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

npm i -D critters

Critical CSS generation will be enabled automatically for you.

Initial State

The initial state comprises data that is serialized to your server-side generated HTML that 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 fetch the data again as the data is fetched during build time and serialized into the page's HTML.

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. For examples, see below:

// 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()
    })
  },
)
// 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 the example of how to use a store with an initial state in a single page app, see the single page example.

State Serialization

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

You may use the option transformState in the ViteSSGClientOptions as displayed 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',
    },
  },
  // ...
})

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 exclude/include route paths to render, or even provide some complete custom ones.

// vite.config.js

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

Comparsion

Use Vitepress when you want:

  • Zero config, out-of-box
  • Single-purpose documentation site
  • Lightweight (No double payload)

Use Vite SSG when you want

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

Cons:

  • Double payload

Example

See Vitesse

Thanks to the prior work

License

MIT License © 2020 Anthony Fu