Daniel Methner
Daniel Methner

Reputation: 607

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

My Server does not serve GZIPd JavaScript files to the client.

I have a Simple Vue.js application, hosted on Heroku. When I build the site via "npm run build" in my console, it populates the /dist/js directory with 4 files for each JavaScript file, as I would expect it to.

So for example:

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

To enable the compression, I installed webpack using the following command:

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

Then I set my vue.config.js to the following:

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

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


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

Basically I followed this tutorial: https://medium.com/@aetherus.zhou/vue-cli-3-performance-optimization-55316dcd491c

When I check the HTTP request in the browser, it says it accepts gzip:

Accept-Encoding: gzip, deflate, br

The point where I get stuck is, making the server actually deliver the .gz files.

In the tutorial it says "The server block of such a static website looks like this:

    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;
      }
    }

But where do I find this block?

This is my 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);

Upvotes: 4

Views: 12849

Answers (1)

Daniel Methner
Daniel Methner

Reputation: 607

The server block is exemplary for NGINX.

When using express, a Node.js compression middleware must be installed.

For Example:

$ npm install compression

The Server js must be adjusted as follows:

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
[...]

Upvotes: 5

Related Questions