One of the most important things of using Webpack is optimizing files.
⚠️Warning: Don’t forget to install the plugins.
We can minificate our files with the plugins css-minimizer-webpack-plugin
for CSS and terser-webpack-plugin
for JS.
note: terser comes with webpack 5, but if we want to configurate it or add other plugins we have to install it anyway.
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
...,
optimization: {
minimize: true,
minimizer: [new CssMinimizerPlugin(), new TerserPlugin()],
},
}
We can use a hash in the names simply adding [contenthash]. However, if we want to attach these to our html file we need to use the html-webpack-plugin
.
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...,
output: {
...,
filename: '[name].[contenthash].js',
},
plugins: [
new HtmlWebpackPlugin({
inject: true, //decide where to put the js scripts (header or body)
template: './public/index.html', //indicate the path of the initial html
filename: './index.html', //this is the default
}),
]
}
see: