#webpack #compression #express #node
It was challenging to group all the information to achieve what I wanted to do; here, I leave you how I created the webpack and related it to express.
this is the plugin section on webpack file: webpack.config.js
example (array of obj)
plugins: [confi1, config2, confi3]
plugins: [
new CompressionPlugin({
filename: '[path][base].gz',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new CompressionPlugin({
filename: '[path][base].br',
algorithm: 'brotliCompress',
test: /\.(js|css|html|svg)$/,
compressionOptions: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11
}
},
threshold: 10240,
minRatio: 0.8
})
]

If you notice, I am using only two compressions, there are more, but I think that with those two, we are fine.
Also, if you want to learn how to modify the opction you can take a look at this page : https://webpack.js.org/plugins/compression-webpack-plugin/
br = Brotli is a lossless data compression algorithm developed by Google)
gzip = is a software library used for data compression (STANDAR). zlib was written by Jean-loup Gailly
I use both for the case that supports br we send br; in case it does not support it we send gzip, and in the worst case we send .js file: we will see it now
How to send the correct file to the client with express:
below...
app.use(
'/static',
expressStaticGzip(path.join('dist', 'frontend'), {
enableBrotli: true,
customCompressions: [
{
encodingName: 'deflate',
fileExtension: 'zz'
}
],
orderPreference: ['br', 'gz'],
setHeaders: function (res, path) {
res.setHeader('Cache-Control', 'public, max-age=0');
}
})
);

look at the files in the image: if you compile with webpack, note the plugins for your JS (br, gz). In this case, bundle.js has a bundle.js.br & bundle.js.gz, and for the CSS, we have the same; if a client makes a request to the folder Static where the files that will be sent to the express client are located, they decide what to send based on the headers in the request. For example, if you use chrome express will send you 'br', but if you use Safari express will send you 'gz'
example for Crome and Safari:
crome: 
example fo safari:

with this, we send the HTML file to the client, and then the client is going to request the js file, but the server will send the js file compress
app.get('/*', function (req, res) {
let pathServer = process.env.subDOMAIN == "true" ? "" : "/scheduler_app";
res.render('pages/index', { App: "stringApp", script: `<script src="${pathServer}/static/bundle.js"></script>`, css: `<link rel="stylesheet" href="${pathServer}/static/main.css">` });
});