Search code examples
javascriptvue.jswebpacksingle-page-applicationprerender

Webpack prerender-spa-plugin with compression-webpack-plugin. index.html not compressed


I'm building a vue cli 3 app with vue-cli-plugin-compression and vue-cli-plugin-prerender-spa installed. (Under the hood these use prerender-spa-plugin and compression-webpack-plugin).

The prerender-spa-plugin renames index.html to app.html. It then prerenders app.html and stores the resulting html in a new index.html. The page is prerendered correctly and app.html is correctly gzipped. However, the resulting index.html (the page that is the result of the prerendering) is not gzipped. How can I get the result of the prerender to be gzipped as well?

Here's my vue.config.js:

module.exports = {
  devServer: {
    port: 3000
  },
  configureWebpack: {
    devtool: 'source-map'
  },
  pluginOptions: {
    prerenderSpa: {
      customRendererConfig: {
        injectProperty: '__PRERENDER_INJECTED',
        inject: {},
      },
      registry: undefined,
      renderRoutes: [
        '/'
      ],
      useRenderEvent: true,
      headless: true,
      onlyProduction: true,
      postProcess: route => {
        // Defer scripts and tell Vue it's been server rendered to trigger hydration
        route.html = route.html
          .replace(/<script (.*?)>/g, '<script $1 defer>')
          .replace('id="app"', 'id="app" data-server-rendered="true"');
        return route;
      }
    },
    compression:{
      gzip: {
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.(js|js\.map|css|html)$/,
        minRatio: 0.8,
      }
    }
  }
};

I tried to prerender before compression, but it doesn't change anything:

chainWebpack: (config) => {
  config.plugin('pre-render').before('gzip-compression');
  config.plugin('gzip-compression').after('html');
},

Solution

  • So, it turns out that the prerender-spa-plugin is outdated and only works for webpack 4, most of the issues have been overcome in webpack 5 with new hooks

    So I refactored the code base of prerender-spa-plugin to work for webpack 5 (and only for it), I also had to remove some features like the html minification as now other compression plugins will correctly run on the html

    You can find the package on npm prerender-spa-plugin-next

    You will need to update your vue cli plugins to the version ^5 to use webpack 5

    As of writing:

    "@vue/cli-plugin-babel": "^5.0.4",
    "@vue/cli-plugin-eslint": "^5.0.4",
    "@vue/cli-plugin-router": "^5.0.4",
    "@vue/cli-service": "^5.0.4",
    "compression-webpack-plugin": "^6.1.1",
    "html-webpack-plugin": "^5.3.1",
    ...
    

    Make sure all of your other dependencies are also updated (Eslint and all the webpack plugins and loaders)

    This might turn into a lot of trial and error to get it to compile after a big update but the trouble is worth it

    Let me know if you have any question regarding the usage of my package