Vue.js webpack 不提供压缩的 GZIP .js 文件

Vue.js with webpack does not serve compressed GZIP .js files

我的服务器不向客户端提供 GZIPd JavaScript 文件。

我有一个简单的 Vue.js 应用程序,托管在 Heroku 上。当我在我的控制台中通过 "npm run build" 构建站点时,它会为每个 JavaScript 文件填充 4 个文件的 /dist/js 目录,正如我所期望的那样。

例如:

chunk-vendors.e26db277.js
chunk-vendors.e26db277.js.gz
chunk-vendors.e26db277.js.map
chunk-vendors.e26db277.js.map.gz

为了启用压缩,我使用以下命令安装了 webpack:

    npm install --save-dev compression-webpack-plugin

然后我将 vue.config.js 设置为以下内容:

    const CompressionPlugin = require('compression-webpack-plugin');

    module.exports = {
      chainWebpack(config) {
        config.plugins.delete('prefetch');


        config.plugin('CompressionPlugin').use(CompressionPlugin);
      }
    };

基本上我遵循了这个教程: https://medium.com/@aetherus.zhou/vue-cli-3-performance-optimization-55316dcd491c

当我在浏览器中检查 HTTP 请求时,它说它接受 gzip:

Accept-Encoding: gzip, deflate, br

我卡住的地方是,让服务器实际传送 .gz 文件。

在教程中说“这种静态网站的服务器块如下所示:

    server {
      listen 80;
      server_name www.example.io;  
      root /path/to/the/directory;
      index index.html;
      gzip_static on;

      location /index.html {
        etag on;
      }
      location / {
        etag off;
        add_header Cache-Control max-age=315360000, immutable;
      }
    }

但是我在哪里可以找到这个块?

这是我的 server.js:

const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')

const app = express()

//here we are configuring dist to serve app files
app.use('/', serveStatic(path.join(__dirname, '/dist')))

// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
  res.sendFile(path.join(__dirname, '/dist/index.html'))
})

const port = process.env.PORT || 8080;
app.listen(port);

服务器块是 NGINX 的典范。

使用 express 时,必须安装 Node.js 压缩中间件。

例如:

$ npm install compression

服务器js必须调整如下:

const compression = require('compression') // <-- import this library
const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')

const app = express()

// use compression
app.use(compression()) // <-- use the library
[...]