/vue-ssr-assets-plugin

Webpack 5 plugin to generate manifest of critical assets for Vue 3 SSR applications

Primary LanguageTypeScriptMIT LicenseMIT

Vue SSR Assets Plugin

This is a Webpack 5 plugin for Vue 3 SSR applications to generate the manifest of critical assets. This package consists of two plugins: one for the client bundle and one for the server bundle similar to how SSR in Vue 2 worked.

Out of the box, Vue 3 SSR loads the entry bundle (e.g. main.js) that then asynchronously loads the remaining files needed for the page. However, this results in a poor user experience due to FOUC and poor web performance scores.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="app">...</div>
    <script src="main.js" defer></script>
</body>
</html>

After

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="/public/main.css"> <!-- New -->
    <link rel="preload" href="/public/main.js" as="script"> <!-- New -->
    <link rel="preload" href="/public/example_src_components_HomePage_vue.js" as="script"> <!-- New -->
</head>
<body>
    <div id="app">...</div>
    <script src="/public/main.js" defer></script>
    <script src="/public/example_src_components_HomePage_vue.js" defer></script> <!-- New -->
</body>
</html>

Client Plugin

This generates a JSON manifest that describes the dependent assets of each Vue component.

import { VueSsrAssetsClientPlugin } from 'vue-ssr-assets-plugin'

const clientEntryConfig = merge(commonConfig, {
    target: 'web',

    entry: {
        main: `${srcDir}/entryClient.ts`,
    },

    plugins: [
        new VueSsrAssetsClientPlugin({
            fileName: 'ssr-manifest.json',
        }),
    ],
})

Example Manifest

{
   "main":{
      "js":[
         "/public/main.36e325f82fb1e4e13943.js"
      ],
      "css":[
         "/public/main.64381ac7ca0c0b20aee8.css"
      ]
   },
   "HomePage.vue":{
      "js":[
         "/public/762.929bac4bc20090ac3b46.js"
      ],
      "css":[

      ]
   },
   "VueComposition.vue":{
      "js":[
         "/public/468.7c2ba2b804d1daa47030.js"
      ],
      "css":[
         "/public/468.ac8a11c16afa837c5a84.css"
      ]
   },
   "VueCompositionSetup.vue":{
      "js":[
         "/public/489.43cf0cdad14c7c1be803.js"
      ],
      "css":[
         "/public/489.afa23172870ddaef0e0e.css"
      ]
   },
   "VueOptions.vue":{
      "js":[
         "/public/599.f92fa658658a699cc9cc.js"
      ],
      "css":[
         "/public/599.ebbf4c878b37d1db1782.css"
      ]
   }
}

Usage with webpack-dev-middleware or webpack-dev-server

If you are using webpack-dev-middleware or webpack-dev-server to serve your frontend during development, then you will need to configure them to write the manifest file to disk instead of keeping the manifest file in their memory file system.

webpack-dev-webpack

import { Configuration } from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import { VueSsrAssetsClientPlugin } from 'vue-ssr-assets-plugin'

export default {
    target: 'web',

    entry: {
        main: './src/entryClient.ts',
    },

    output: {
        path: './dist/client'
    },

    devServer: {
        index: 'index.html',
        devMiddleware: {
            writeToDisk: (filePath) => filePath.includes('ssr-manifest.json'),
        },
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            filename: './dist/client/index.html',
        }),
        new VueSsrAssetsClientPlugin({
            fileName: './dist/server/ssr-manifest.json',
        }),
    ],
} satisfies Configuration

webpack-dev-middleware

import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import express from 'express'

const app = express()
const compiler = webpack({ /* Client Config */ })

app.use(
    webpackDevMiddleware(compiler, {
        writeToDisk: (filePath) => filePath.includes('ssr-manifest.json'),
    }),
)

Server Plugin

This modifies the ssrRender function that vue-loader automatically generates from your <template> tag in your SFC. At runtime, each component will register their webpack chunk name into ssrContext._matchedComponents: Set<string>(). Each name will correspond with a key in the manifest generated by the client plugin that you can then use to look up the critical assets for the current request.

import { VueSsrAssetsServerPlugin } from 'vue-ssr-assets-plugin'

const serverEntryConfig = merge(commonConfig, {
    target: 'node',

    entry: {
        www: `${srcDir}/entryServer.ts`,
    },

    output: {
        libraryTarget: 'commonjs2',
    },

    plugins: [
        new VueSsrAssetsServerPlugin(),
    ],
})

Example Usage

import App from './App.vue'
import { createSSRApp } from 'vue'
import { createRouter } from 'vue-router'
import { renderToString } from '@vue/server-renderer'
import { readFileSync } from 'node:fs'
import { VueSsrAssetRenderer } from 'vue-ssr-assets-plugin/dist/utils/VueSsrAssetsRenderer'

/**
 * After renderToString(), ssrContext._matchedComponents will contain
 * all the components that this request needs e.g. ['MainLayout.vue', 'HomePage.vue']
 *
 * These can then be matched with the dict in ssr-manifest.json to find all the critical js/css files
 *
 * VueSsrAssetRenderer is a helper class that reads the ssrContext
 * and generates the corresponding <script> and <link> tags
 */
const assetRenderer = new VueSsrAssetRenderer('/path/to/ssr-manifest.json')

async function handleRequest(req, res) {
    const ssrContext = {
        _matchedComponents: new Set<string>(),
    }

    const app = createSSRApp(App)
    const router = createRouter()
    await router.push(req.originalUrl)
    app.use(router)

    const appHtml = await renderToString(app, ssrContext)
    const { header, footer } = assetRenderer.renderAssets(ssrContext._matchedComponents)

    res.setHeader('Content-Type', 'text/html')
    res.status(200)
    res.send(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            ${header}
        </head>
        <body>
            <div id="app">${appHtml}</div>
            ${footer}
        </body>
        </html>
    `)
}

Important: You need to import the full path to VueSsrAssetsRenderer instead of the index file because this package is generated as a CommonJS format for compatibility with older NodeJS runtimes. As a result, Webpack cannot tree shake this Webpack plugin that's also imported inside the index file. If you tried to import the index file in your runtime code, then your production bundle will try to import webpack which should be a devDependency and crash.

See the example directory for a full example.