【问题标题】:Webpack prerender-spa-plugin with compression-webpack-plugin. index.html not compressedWebpack prerender-spa-plugin 和compression-webpack-plugin。 index.html 未压缩
【发布时间】:2020-11-29 09:35:12
【问题描述】:

我正在构建一个安装了 vue-cli-plugin-compression 和 vue-cli-plugin-prerender-spa 的 vue cli 3 应用程序。 (在后台这些使用 prerender-spa-plugin 和 compression-webpack-plugin)。

prerender-spa-plugin 将 index.html 重命名为 app.html。然后它预渲染 app.html 并将生成的 html 存储在新的 index.html 中。该页面已正确预呈现,并且 app.html 已正确压缩。但是,生成的 index.html(作为预渲染结果的页面)是 gzip 压缩的。我怎样才能让预渲染的结果也被压缩?

这是我的 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,
      }
    }
  }
};

我尝试在压缩之前进行预渲染,但它并没有改变任何东西:

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

【问题讨论】:

  • 我一直在寻找解决同样问题的方法,但是 prerender 插件在其他所有内容之后运行。所以它不会工作,我想你需要重新运行压缩脚本之后

标签: javascript vue.js webpack single-page-application prerender


【解决方案1】:

所以,事实证明 prerender-spa-plugin 已经过时并且仅适用于 webpack 4,大多数问题已经在 webpack 5 中通过新的钩子解决了

所以我重构了 prerender-spa-plugin 的代码库以适用于 webpack 5(并且仅适用于它),我还必须删除一些功能,如 html 缩小,因为现在其他压缩插件将在 html 上正确运行

你可以在 npm prerender-spa-plugin-next找到这个包

你需要将你的 vue cli 插件更新到 alpha 版本才能使用 webpack 5

截至发稿时:

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

确保所有其他依赖项也已更新(Eslint 和所有 webpack 插件和加载器)

这可能会变成大量的试验和错误,以便在大更新后编译它,但麻烦是值得的

如果您对我的包裹的使用有任何疑问,请告诉我

【讨论】:

  • 我已经离开了那个项目,但答案看起来不错。所以我会接受这个作为答案!