How can I get the chunkhash value generated by webpack4 so that I can use it inside my index.html
to set properly the script src?
Brief context: Hope it not to be a stupid question because I am completely newcomer in webpack, started to learn today. I know how to config, extract js, css, minify them, and maybe all the very basic operations.
This is my webpack.config.js
:
const path = require('path')
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptmizerCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: '[chunkhash].bundle.js' // <<<<<<
},
mode: 'development',
optimization: {
minimizer: [
new TerserPlugin({}),
new OptmizerCssAssetsPlugin({})
],
splitChunks: {
chunks: 'all'
}
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
},
{
test: /\.css$/,
use: [
{ loader: MiniCssExtractPlugin.loader },
'css-loader'
]
}
]
},
plugins: [
new webpack.ProvidePlugin({
cowsay: 'cowsay-browser'
}),
new MiniCssExtractPlugin({
filename: 'css/[name].css'
})
]
}
The relevant part is in filename: '[chunkhash].bundle.js'
that will produce a filename like 6f9e5dd33686783a5ff8.bundle.js
.
I can use that name in my html like <script src="dist/6f9e5dd33686783a5ff8.bundle.js"></script>
but I would have to change it everytime the code was updated/regenerated.
I was able to use filename: '[name].bundle.js'
instead of the chunkhash
but it is not good for caching porpouses.
So, is there any way I can get the chunkhash
value and use it to set my script src filename in my index.html
automatically everytime I build the project?
Any valid advice will be wellcome!