I am trying to inject css file into my index.html. Currently my web pack does the following
output of the folder structure:
- Dist
- OptionA
- optionA-hash.css
- OptionB
- optionB-hash.css
- index.html //How to inject above css into this file?
I am new to HtmlWebpackPlugin my question is how do i inject above dynamic css files into the index.html? so that in the head section i have the following:
<link href="optionA-32d6cb.css" rel="stylesheet">
<link href="optionB-w2d6cb.css" rel="stylesheet">
My webpack.config.js file:
module.exports ={
entry: ['path_to_scss_file'],// SASSfile which contains import statment with wildcard to get all sass in given directory
output: {
filename: "[name].min.js",
path: path.resolve(__dirname, 'dist/'),
},
plugins:[
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module:{
rules: [
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options:{
name:'[name]/[name]-[contenthash].css',
}
},
{
loader: 'sass-loader',
options: {
sassOptions: {
importer: globImporter(),
//my sass files uses wildcard to import all sass files
},
},
}
]
}
]
}
You can use webpack-manifest-plugin to solve this issue which will create a manifest.json file inside the dist/ folder.
The manifest.json file will contain all the mappings like this
{
"app.css": "css/app.dc4d6b6c65b4f5ff351e.css"
}
and then use HtmlWebpackPlugin, it will do the job every time you build, it will inject the correct files to index.html
by referring to manifest.json
Refer https://github.com/anandgupta193/react-enterprise-starter-kit for an exact working implementation in webpack/webpack.common.config.js file. (use node 12.x to create a build in the starter kit)
Note: Remove your scripts and link tags from the index.html template, it will get injected automatically.