Friday, 16 March, 2018 UTC


Summary

A while ago, when building a lot of front end applications, once a change is made, the we browser needs to be reloaded every time. At that time, this didn’t seem like a problem at all. As the saying goes, necessity is the mother of inventions. How about we not having to manually reload our browser when we make changes to our applications? In comes webpcak!!!!.
webpack is a static module bundler that has come to stay in the development of our modern javascript applications. This only makes sense though because having to manually refresh the browser every time a single change is made to the application can get really tiring.
How Does webpack Work?
webpack take all the modules in your application ( HTML, CSS , JS, Fonts ) and continuously builds a dependency graph of your application then puts them into one or more bundles. Now the only little caveat is it’s configuration. Most people shy away from webpack because they have a conception that the configuring webpack for your application is too much of a herculean task that they’ll rather not use it. In comes webpack 4 - code name - with very little configuration needed to get you up to speed!
What we’ll build
In this article, we are going to build a simple weather forecasting application and use webpack during development to show how to easily and seamlessly include webpack 4 into your development process.
Dependencies
Before we get to building, we need to make sure we have the following dependencies met on our local machines :
  • Node installed on your machine,
  • Node Package Manager (NPM) installed on your machine
To confirm your installation, run the following command on your terminal :
node --version
npm --version
If you get version numbers as results then it means you’re well underway to getting started. If you don’t, head over real quick to their downloads page and then comeback to follow through.
Create your application
In your terminal, we first create a new folder,
mkdir weather-forecaster
Then run npm init
cd weather-forecaster
npm init
Now, the next thing we need to do is to add webpack to our project and to do this, we run the command :
npm install webpack webpack-cli -D
💡 : webpack is currently on version 4.1.1 at the time of this article and we will be talking about configurations with regards to this version
Creating Necessary Files
Create a directory called src which will contain our necessary source files
mkdir src
cd src 
touch index.js 
In our index.js , we have the following:
alert("It's going to rain today! Take your umbrella");
Using webpack with Zero Configurations
In previous versions of webpack, we would need to create a webpack.config.js file to specify at least the : entry point - Where the dependency graph should start from output - where the resulting bundle should be stored and what name to give to it
With webpack 4, wait for it …. you can get started with ZERO CONFIGURATIONS!!!
webpack automatically assumes the **./src/index.js** for the entry point of our project and will automatically spit the result to **./dist/main.js** . Of course, this can be altered to fit our custom needs.
Specifying webpack Mode In our package.json, we add the following :
    {
      //...
      "scripts" : {
        // ...
        "dev": "webpack --mode development",
        "build": "webpack --mode production"
      }
      //...
    }
In the above, we are adding run scripts and specifying if we are running in production/development mode.
Now, when we run npm run dev , we get the result below :
The result is also stored in the ./dist/main.js.
NOTICE how we never set any configurations….
Using Result Bundle in Application
Now, we create an index.html file in the root directory of our application and have the following:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Weather Forecaster</title>
    </head>
    <body>
        <h1>Taking webpack for a Spin ....</h1>
        <script src="./dist/main.js"></script>
    </body>
    </html>
In our index file above, we include the built bundle created by webpack ( see line 11 ). Now when we run it, we get the following :
Adding the webpack Dev Server At this point, we need to run npm run dev every single time for webpack to re-bundle our assets. This is not the most ideal way to do things. In comes the webpack-dev-server . The webpack development sever will launch a browser window and refresh your window whenever a change to a file is made.
To install the development server, run the following command :
npm install webpack-dev-server --save-dev
The webpack development server is not intended for production mode
Once this is done, we need to edit our package.json again to have the following
    {
      //...
      "scripts" : {
        // ...
        "dev": "webpack-dev-server --mode development --open",
        "build": "webpack --mode production"
      }
      //...
    }
Now, once this is done and we hit npm run dev , we get the following :
Now that the webpack dev Server is running, any time a change is made to our scripts, our modules are re-bundled again and served on the browser page without us performing any actions
💡 : All this happened with ZERO CONFIGURATIONS!!!
Deeper Look into webpack Configurations
Now that we have gotten the basics of how webpack works, let’s take a deeper look at the webpack 4 configurations and how we’ll use them in our weather-forecaster application.
First, we need to create our webpack.config.js as this will hold all our webpack configurations.
touch webpack.config.js
If the scripts for your application is such that they need to be compiled into more than one bundle, then we need to specify our entry points but before we continue, we need to talk about two other webpack concepts :
  • Plugins
  • Loaders
Configuring Plugins Earlier on, we manually created our index.html file ourselves. This is not the only way to get our index.html file. We can make use of the html-webpack-plugin . We will not look at how to dynamically generate a our index.html
  • Firstly, we need to delete the manually created index.html
  • Install the **html-webpack-plugin**
To install the webpack-plugin, we run the following command in our terminal :
npm install html-webpack-plugin
  • Create **index.html** template
In our src/ folder, we create an index.html template file which our final page will be built from.
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>
            <%= htmlWebpackPlugin.options.title %>
        </title>
    </head>
    <body>
        <h1>Weather in your location is 19 degrees and its raining</h1>
    </body>
    </html>
Notice how the placeholders are specified in the template
  • Edit our **webpack.config.js** to include the plugin
Now, we need to then use the plugin. To do this, we tweak our webpack.config.js :
    var HtmlWebpackPlugin = require("html-webpack-plugin");
    module.exports = {
      plugins: [
        new HtmlWebpackPlugin({
          hash: true,
          title : 'Weather Forecaster',
          template : './src/index.html'
        })
      ]
    };
We specify where the template is and also enter what title we intend to give our page.
Configuring Loaders By default, webpack only loads javascript files. To allow webpack load other resources like css, ts, scss , we are going to make use of Loaders. We will be using the css-loader that helps collect CSS from all raw referenced css files and the style-loader will then place the output obtained from the css-loader and put it inside the <style> tags in the index.html file.
  • Installing the css-loader and style-loader
To install the loaders, we run the command
npm install css-loader style-loader--save-dev
  • Create .css file
In our src/ folder of the app, we create our app.css
touch app.css
Now, our app.css can look like this
    h1 {
      color: green;
      padding-left : 50px;
    }
  • Using **css-loader** and **style-loader** in webpack config
Now, our webpack.config.js should look like this :
    module.exports = {
      [...]
      module: {
        rules: [
          {
            test:/\.css$/,
            use:['style-loader','css-loader']
          }
        ]
      }
    }
What the above is saying is that files with name matching the regular expression should use the css-loader and then the style-loader on the result of the css-loader
webpack applies loaders from right-to-left , hence [‘style-loader’,’css-loader’]
  • Include the style as a dependency in our **index.js**
If we do not include the style as a dependency in our index.js , the app.css file will not be bundled by webpack because we haven’t included the file at all.
We include the file by updating our index.js to look like this :
import './app.css';

alert("It's going to rain today! Take your umbrella");
Running application
Earlier on, we specified some run scripts in our package.json folder. Now we just need to run the command depending on what we need to do.
In this case we are just testing out the application, so we run :
npm run dev
This starts our application for us with live reloads enabled.
Conclusion
In this article, we looked at the basic steps involved in getting started with webpack 4 using zero configurations. We also looked at how to enable automatic and continuous live reloads using the webpack dev server. There’s still so much more that can be done w webpack but you’re well underway to suing it confidently in your applications. Here’s a link to the full github repository if you’re interested.