cssreactjspluginswebpack.config.js

Mini-css-extract-plugin - how grap the hash naming on index.html


I try currently to implement mini-css-extract-plugin.

I fail to implement hash naming, when I use it I don't know how lead my index.html file to grap the specific name on the fly.

If someone has any idea would be great.Thanks

Here my webpack.config.js :

plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: 'styles.[contenthash].css'
    })
  ],
module: {
   rules: [ {
     test: /\.js|jsx$/,
     exclude: /node_modules/,
   include: path.resolve(__dirname, "src"),
     use: [
       {
   loader: "babel-loader",
   options: {
     presets: ["es2015", "stage-1", "react"]
   }
       }
     ]
   },

   {
   test: /\.css$/,
   use: [{
     loader: MiniCssExtractPlugin.loader,
     options: {
       publicPath: "./public"
     }
   }, {
     loader: "css-loader"
   }]
 }

]},

here my index.html:

<link rel="stylesheet" href="styles.css">

how translate in my html the "[contenthash]" part of my css filename ?


Solution

  • Here my basic understanding of html-webpack-plugin (thereafter HWP).

    Seems that HWP create a kind of meta-bundle in which all bundles are merged. Your loaded CSS, JS, HTML bundles will be regrouped in the HWP file hence created.

    The links to each loaded files will be automatically added to your HWP bundle.

    Keep in mind that the HWP file's body comes virgin of any text, so, how reach HTML DOM elements in these conditions ?*

    If you use Reactjs or other JavaScript library for building user interfaces, you will need to reach some DOM elements. To include theses DOM elements in your HWP, you have just to load a template file. The content of this template will be include in your HWP bundle. So you keep an access on your DOM elements and can handle your HTML code, great.

    To create a template, enter these parameters in your webpack.config.js :

      plugins: [
               new HtmlWebpackPlugin({
                (...)
                  template:  "path to your template.html",
                (...)                  
                })
      ];
    

    Keep in mind that your path will be influenced by the context of your webpack.config.js.

    It's up to you now