Vue.js结合webpack无法提供压缩后的GZIP文件.js。

4

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

我有一个简单的Vue.js应用程序,托管在Heroku上。当我通过控制台运行“npm run build”来构建网站时,它会像我预期的那样为每个JavaScript文件在/dist/js目录中填充4个文件。

因此,例如:

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);
1个回答

5

这个服务器块是 NGINX 的典范。

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

例如:

$ npm install compression

必须按以下方式调整Server 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
[...]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接