WebPack: Part-2
Tags: webpack, javascript, beginners, webdev
Published: 2020-06-12 06:56:55

<!-- wp:paragraph -->
<p>In <a href="http://blog.suprabha.me/tools/webpack/">previous blog</a>, we have discussed the concepts of webpack setup and loaders.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In this Blog, We will be discussing on:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Cache Busting and plugins</li><li>Splitting dev and production</li></ol>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3><strong><span class="has-inline-color has-vivid-red-color">Cache Busting and Plugins:</span></strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://webpack.js.org/guides/caching/"><strong>Cache busting</strong></a> is how can we prevent certain assets like main bundle js or css bundle, &nbsp;once we create separate CSS bundle.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Whenever we do some changes in code then it should generate the new hash or else the hash should be same every time even while refreshing the page. So, it means the URL gets cached if there will be no changes in code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>webpack.config.js:</strong></p>
<!-- /wp:paragraph -->

```js
const path = require("path")

module.exports = 
  { 
    entry: "./src/index.js",
    output: 
      { 
         // the first thing we can configure is file name
         filename: "vendor.[contentHash].js",
         // contentHash Will generate hash
         // where to do , where to actually split the code 
         // Import path from module which comes with node called path 
         // path.resolve(__dirname,..) : It mainly resolve absolute path to the New_folder_name   directory. Wherever the current directory is. e.x. in my lappy: /Users/Projects/ Work/webpack-work // "dist" name of the folder where we want to code be going path: path.resolve(__dirname, "New_folder_name") } }
      }
}
```

<!-- wp:paragraph -->
<p>In my earlier&nbsp;blog(<a href="http://blog.suprabha.me/tools/webpack/">webpack: part 1</a>),&nbsp;we were kept <code>dist/main.js</code> into index.html file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But when we generate the file through hash, then we no need to include script into index.html. That can doable by using plugins.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3><strong><span class="has-inline-color has-vivid-red-color">Plugins</span>:</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://webpack.js.org/plugins">Plugins</a>&nbsp;used to customize the webpack build process in variety of ways.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will talk about&nbsp;<strong>HTMLWebpackPlugin</strong>:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<a href="https://github.com/jantimon/html-webpack-plugin">HtmlWebpackPlugin</a>&nbsp;simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using&nbsp;<a href="https://lodash.com/docs#template">lodash templates</a>, or use your own&nbsp;<a href="https://webpack.js.org/loaders/">loader</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Install&nbsp;<strong>HTMLWebpackPlugin</strong></p>
<!-- /wp:paragraph -->

<!-- wp:codemirror-blocks/code-block {"mode":"javascript","mime":"text/javascript","theme":"duotone-light"} -->
<div class="wp-block-codemirror-blocks-code-block code-block"><pre>$ npm install —save-dev html-webpack-plugin</pre></div>
<!-- /wp:codemirror-blocks/code-block -->

<!-- wp:paragraph -->
<p><strong>webpack.config.js:</strong></p>
<!-- /wp:paragraph -->

```js
const HtmlWebpackPlugin = require('html-webpack-plugin');

// then we can add plugins in module: 
plugins: [new HtmlWebpackPlugin()],
```

<!-- wp:paragraph -->
<p>Now, while doing&nbsp;<em><strong>npm start,</strong></em>&nbsp;which will create&nbsp;<strong>index.html</strong>&nbsp;inside&nbsp;<strong>dist</strong>&nbsp;folder where the script will be included automatically.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But there will be no content on the page. As previously we were taking another index.html and now its taking dist/index.html file where only script has been added not the HTML content.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Create new html file inside&nbsp;<strong>src</strong>&nbsp;folder as main.html</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And copy the code of previous index.html file into main.html. Remove script tag was taken from webpack previously.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Remove:</p>
<!-- /wp:paragraph -->

```html
<script src="/dist/main.js" ></script>
```

<!-- wp:paragraph -->
<p>Now we need to tell plugin to use the template which we have created. (main.html)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>webpack.config.js:</strong></p>
<!-- /wp:paragraph -->

```js
const path = require("path")
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = 
  { 
    mode : "development"
    entry: "./src/index.js",
    output: 
      { 
         filename: "hello.js", 
         path.resolve(__dirname, "New_folder_name") } }
      },
    plugins: [
      new HtmlWebpackPlugin({ 
template: "./src/main.html"
       })
    ],
    module: 
       { 
         rules: [ 
           { 
  // files which ends with .css use the below loader 
   test: /\.scss$/,
   use: [
"style-loader", // 3rd. style loader inject styles into DOM
"css-loader", // 2nd. CSS loader turns css into common JS
"sass-loader" //1st. SASS loader which turns sass into CSS
}
         ]
     }
}
```
<!-- wp:paragraph -->
<p>Now do&nbsp;<strong><em>npm start</em>,</strong>&nbsp;we can see&nbsp;<strong>dist/index.html</strong>&nbsp;where the template will be there from main.html.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3><strong><span class="has-inline-color has-vivid-red-color">Splitting DEV and Production:</span></strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We can create two file in root as:&nbsp;<strong>webpack.dev.js</strong>&nbsp;and&nbsp;<strong>webpack.prod.js</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And copy the code of webpack.config.js into both files.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, I will be making one common config file for webpack called webpack.config.js</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Later, We need to merge the webpack.dev.js with webpack.config.js and webpack.prod.js with webpack.config.js</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To merge the file install plugin called&nbsp;<strong>webpack-merge</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em>$ npm install —save-dev webpack-merge</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>webpack.dev.js:</strong></p>
<!-- /wp:paragraph -->

```js
const path = require("path")
const common = require('./webpack-config');
const merge = require('webpack-merge');

module.exports = 
 merge(common ,{ 
    mode : "development"
    output: 
      { 
         filename: "hello.js", 
         path.resolve(__dirname, "New_folder_name") } }
      }
})
```
<b>webpack.prod.js:</b>
```js
const path = require("path")
const common = require('./webpack-config');
const merge = require('webpack-merge');

module.exports = 
  merge(common, { 
    mode : "production"
    output: 
      { 
         filename: "hello.[contentHash].js", 
         path.resolve(__dirname, "New_folder_name") } }
      }
})
```

<b>webpack.config.js:</b>
```js
const path = require("path")
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = 
  { 
    entry: "./src/index.js",
    plugins: [
      new HtmlWebpackPlugin({ 
template: "./src/main.html"
       })
    ],
    module: 
       { 
         rules: [ 
           { 
  // files which ends with .css use the below loader 
   test: /\.scss$/,
   use: [
     "style-loader", // 3rd. style loader inject styles into DOM
     "css-loader", // 2nd. CSS loader turns css into common JS
     "sass-loader" //1st. SASS loader which turns sass into CSS
       ]
     }}
  }

```
<!-- wp:paragraph -->
<p>Now, we can change package.json according to dev and prod:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>package.json:</strong></p>
<!-- /wp:paragraph -->

```json
"scripts": 
     {
        "start" : "webpack --config webpack.dev.js",
        "prod" : "webpack --config webpack.prod.js"
      }
```

<!-- wp:paragraph -->
<p>Check the command by running npm start for dev and npm run prod for production.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Currently, whenever we are making changes every time we have to run npm start to build the dev. We can fix this by setup webpack dev server.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Install&nbsp;<strong>webpack-dev-server:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>$&nbsp;<em>npm install —save-dev webpack-dev-server</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In&nbsp;<strong>package.json:</strong></p>
<!-- /wp:paragraph -->

```json
"scripts": 
     {
       "start" : "webpack-dev-server --config webpack.dev.js",
       "prod" : "webpack --config webpack.prod.js"
      }
```

<!-- wp:paragraph -->
<p>--open will open the browser in window for us. It works as live server. You can change the code and webpack server will automatically rebuild and refresh the browser for us.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I hope you found this blog helpful, If you have any question please reach out to me on <strong><a href="https://twitter.com/suprabhasupi">@suprabhasupi</a> 😋</strong></p>
<!-- /wp:paragraph -->

<table>
  <tbody>
    <tr>
      <td>
        🌟 <a href="https://twitter.com/suprabhasupi"> Twitter</a>
      </td>
      <td>
        👩🏻‍💻 <a href="https://www.suprabha.me/"> Suprabha.me</a>
      </td>
<td>
        🌟 <a href="https://www.instagram.com/suprabhasupi/"> Instagram</a>
      </td>
    </tr>
  </tbody>
</table>