Nullifying Precipitation Machine
    Wondering what’s next for npm?Check out our public roadmap! »

    prerender-vue-webpack-plugin

    2.1.0 • Public • Published

    Prerender Vue Webpack Plugin

    A Webpack plugin that allows you to prerender your Vue applications and optionally inline critical CSS at build time without a headless browser. For prerendering, this plugin depends on the bundle renderer from vue-server-renderer and the bundle-source map file generated by vue-server-renderer/server-plugin. For inlining critical CSS, the plugin uses Critters as a client.

    prerender-vue-webpack-plugin npm

    Installation

    As mentioned, this plugin depends on vue-server-renderer@>=2.x to work. That package is defined as a peer dependency of this plugin, meaning you'll need to install it separately before using this plugin.

    $ npm i -D vue-server-renderer

    Next, bring the plugin into your project

    $ npm i -D prerender-vue-webpack-plugin

    Finally, import VueSSRServerPlugin and the plugin into your Webpack configuration and add it to your array of plugins.

    // webpack.config.js
    +const VueSSRServerPlugin = require('vue-server-renderer/server-plugin');
    +const PrerenderVueWebpackPlugin = require('prerender-vue-webpack-plugin');
     
    module.exports = {
      plugins: [
    +    new PrerenderVueWebpackPlugin({
    +      // Configuration (see below)
    +    }),
    +    new VueSSRServerPlugin()
      ]
    }

    Configuration options

    Properties

    • entry <required, String> The entry corresponding to the emitted asset representing the Vue application
    • template <required, String> The path to the template to be transformed.
    • templateContext <optional, Object, default: {}> The context data used in the bundle rendering process
    • root <optional, String, default: {@link VUE_APP_ROOT}> The root element in the template used by the Vue application
    • serverBundleFileName <required, String, default: {@link SERVER_BUNDLE_FILE_NAME}> The file generated by vue-server-renderer/server-plugin.
    • overwrite <optional, Boolean, default: false> If true, prioritizes the {@link this.template} path as the output path.
    • outputPath <optional, String, default: {@link this.compilerOutput}> The path to output the transformed HTML to
    • outputFileName <optional, String, default: {@link this.entry}.html> The outputted file name for the transformed html
    • hook <optional, Function> Hook into the compilation process before any transformations begin.
    • critters <optional, Object> An object that allows you to set/overwrite options passed to the Critters client.
    • inlineCSS <optional, Object> Use Critters to inline critical CSS into the {@link this.template}.
    • inlineCSS.entries <optional, String[]> An array of entries/chunks whose CSS assets are used by the Vue app.
    • inlineCSS.externals <optional, String[]> An array of external assets that should be dynamically included in the compilation process via {@link this.hook}.
    • inlineCSS.mergeCSS <optional, Boolean, default: true> Merges the {@link entries} and {@link externals} into a single sheet and is passes to Critters. If false, individual sheets from both groups are processed separately by Critters.

    Example usage

    Prerender a Vue application

    new PrerenderVueWebpackPlugin({
      entry: "details", // Vue application entry point
      root: "#app", // The element from the template that the app hooks
      template: "src/main/resources/templates/details.html", // path to template
    })

    Prerender multiple Vue applications

    plugins: [
      new PrerenderVueWebpackPlugin({...}),
      new PrerenderVueWebpackPlugin({...}),
    ]

    Add data to the application

    new PrerenderVueWebpackPlugin({
      entry: "details",
      root: "#app",
      template: "src/main/resources/templates/details.html",
    + templateContext: mockData, // Data passed to the template during bundle rendering
    })

    Inline critical CSS into the template

    new PrerenderVueWebpackPlugin({
      entry: "details",
      root: "#app",
      template: "src/main/resources/templates/details.html",
      templateContext: mockData,
    + inlineCSS: {
    +   // Entries/chunks corresponding to the app styles
    +   entries: [
    +     "global-style",
    +     "details-style"
    +   ],
    + }
    })

    Inline critical fonts (passing options to Critters)

    new PrerenderVueWebpackPlugin({
      entry: "details",
      root: "#app",
      template: "src/main/resources/templates/details.html",
      templateContext: mockData,
      inlineCSS: {
        entries: [
          "global-style",
          "details-style"
        ],
      },
    + critters: {
    +   inlineFonts: true
    + }
    })

    Advanced use case

    Critters relies on stylesheets built into the Webpack compilation process. If we want to inline critical external stylesheets, we must add them to the compilation assets before Critters runs. This plugin provides a client hook into the compilation process before transformations begin.

    Perhaps our external stylesheets live on a server. Here is an example of incorporating them into the compilation for Critters. Here is the hook:

    const phin = require('phin');
    const https = require('https');
    const path = require('path');
    const fsPromises = require('fs').promises;
     
    /**
     * Brings in a custom Webpack manifest to pull the URLs of the external
     * CSS assets used by the application that we want to inline. Then, adds
     * them to the {@link compilation} so that Critters can process them.
     *
     * @param   {Object}  compiler     Webpack compiler object
     * @param   {Object}  compilation  Webpack compilation object
     *
     * @return  {void} 
     */
    async function addExternalStylesheets(compiler, compilation) {
      const { externals = {} } = config;
      const customManifest = JSON.parse(await fsPromises.readFile(
        path.resolve(compiler.options.output.path, 'manifest.json')
      ));
      return Promise.all(
        Object.keys(externals).map(async (externalKey) => {
          const cssUrl = Object.values(customManifest[externalKey]).find(
            asset => /\.css(\?[^.]+)?$/.test(asset)
          ) || '';
          try {
            const { body } = await phin({
              url: cssUrl,
              timeout: 2000,
              core: {
                agent: new https.Agent({
                  rejectUnauthorized: false,
                }),
              },
            });
            const cssSource = body.toString();
            // eslint-disable-next-line no-param-reassign
            compilation.assets[externalKey] = {
              source() {
                return cssSource;
              },
              size() {
                return cssSource.length;
              },
            };
          } catch (error) {
            console.log(error);
          }
        })
      );
    }

    Now we use the hook:

    new PrerenderVueWebpackPlugin({
      entry: "details",
      root: "#app",
      template: "src/main/resources/templates/details.html",
      templateContext: mockData,
    +  // Add the hook
    +  hook: addExternalStylesheets,
      inlineCSS: {
        entries: [
          "global-style",
          "details-style"
        ],
      },
      critters: {
        inlineFonts: true
      },
    })

    Lastly, we need to tell PrerenderVueWebpackPlugin to pass these external stylesheets to Critters. The name of the sheets should match the asset/file name(s) that we included in the compilation. So, for the case of using the above hook, whatever the externalKeys happen to be.

    new PrerenderVueWebpackPlugin({
      entry: "details",
      root: "#app",
      template: "src/main/resources/templates/details.html",
      templateContext: mockData,
      // Add the hook
      hook: addExternalStylesheets,
      inlineCSS: {
        entries: [
          "global-style",
          "details-style"
        ],
    +   externals: [
    +     'externalKey' // This should be an actual asset name
    +   ]
      },
      critters: {
        inlineFonts: true
      },
    })

    Install

    npm i prerender-vue-webpack-plugin

    DownloadsWeekly Downloads

    6

    Version

    2.1.0

    License

    MIT

    Unpacked Size

    32.6 kB

    Total Files

    7

    Last publish

    Collaborators

    • avatar