Baby Steps with Webpack

Toyin Olawale
Webtips
Published in
4 min readJul 25, 2020

--

What is Webpack?

Webpack is a module bundler that takes custom files to generate static assets to represent those modules. Modules are chunks of functionalities that make up your full program. It simply means to take a fully dynamic application and package it all up into static file(s) which you can then upload and deploy to the server.

I’m going to use really simple terms henceforth..almost like giving milk to a baby. Webpack really shines when you have a large application with numerous files that have dependencies and other dependencies’ dependencies, as we are going to quickly look at.

For Instance, if I’m creating a simple web app that performs a simple mathematical calculation. I share the functionality of this program into a main app.js file, containing my click event listeners that enables my functions to be executed. This app.js files depends on a function.js file that contains my add, subtract, multiply and divide functions, and then probably an object.js that contains various objects we will need in our app. **This is just hypothetically speaking but I hope you get the gist🤔**.

You will load these scripts in your index.html file as shown below.

<script src="app.js"></script>
<script src="function.js"></script>
<script src="objects.js"></script>

But during deployment, we have no control of what file gets parsed and executed first and this is what Webpack will help us to manage. Wouldn't it be nice if we can have a single .js file that includes all these other files and manages our dependencies??

Let's see how it really works. But first we have to set up our package.json file by running npm init -yon the terminal.
In our package.json file, set "private" : "true" to prevent it from being published on npm. Erase all scripts as we will add ours later.

Installing Webpack.

To install, run on the terminal npm install --save-dev webpack
This will prompt you to install another package that will be added to the dev dependencies in our package.json file. Run on the terminal;

npm install --save -dev webpack webpack -cli

Remember the scripts we deleted earlier? we want to set up our own scripts now using:

"scripts" : {
"start" : "webpack"
},

To call webpack run npm start

We only just installed webpack and its default behavior. This behavior includes setting a default entry point to index.js and mode as production. So if you have no js file called index.js, an error will be thrown because it will not know it’s entry point. I will explain what entry point means in a bit. Please keep following along…

To quickly resolve that error, create an index.js file and rerun npm start
This will create a folder called dist and a file called main.js. This are the default methods before we set up our configuration.

Configuring Webpack
Remember I said webpack is going to grab all the relevant dependencies and put them all in a file, but first we have to declare which file depends on what using ES6 imports and exports. Using our hypothetical calculator example:

//this is our app.js fileconst addBtn = document.getElementById ('add-btn');
const subtractBtn = document.getElementById ('subtract-btn');
addBtn.addEventlistener('click',addFunct);
sutractBtn.addEventlistener('click',subtractFunct);
//notice that our addFunct and subtractFunct are not in this app.js file but in our function.js file.

We need to import these functions from our function.js file because app.js file depends on it. We import it using the code :

import {addFunct} from "./index/function";
import {addFunct} from "./index/function";

where ‘./index/function’ is your path to file, depending on how it is saved on your workspace. The code snippet above is added to your app.js file so webpack is aware of them.

Then in our function.js file, we export these dependencies to be made available to where they will be needed. Still using our calculator example,

export function addFunct(a,b){
console.log (a+b)};
export function subtractFunct (a,b) {
console.log (a-b)};

Webpack is now aware of these dependencies using the export keyword.

Now create a webpack.config.js file, inside that file create an export module:

const path = require ('path');module.exports = {
mode: 'development'
entry : 'app.js'
output: {
filename: 'bundle.js'
path : path.resolve(__dirname, 'dist')
}
};
  1. Entry point signifies where our webpack should start reading from and taking note of all the dependencies. For more details, click entry points.
  2. Output indicates where webpack has compiled all the files and in our case, it is called bundle.js. For more details, click output.
  3. path: path.resolve (__dirname, 'dist') simply creates a path with the current directory and the name of the folder, dist.

Webpack will now create a new folder called ‘dist’, and inside a file called ‘bundle.js’.

Then go back to package.json file and set

"scripts" : {
"start" : "webpack --config webpack.config.js"
},

All this may feel overwhelming at first, but trust me If you follow these baby steps judiciously, I’m sure you will get a hang of it.

Now instead of putting all 3 of our .js files (app.js, function.js,object.js) in script tags, we can just only use the bundle.js file that webpack has created for us:

<script src="bundle.js"></script>

Bundle.js is that single file that will used and our calculator will still work perfectly!

LOADERS

Webpack works basically with javascript, but we have loaders that can allow webpack handle and pre-process different types of files besides javascript. Some popular loaders includes CSS, babel etc.

For instance, if your application has a large number of CSS files, webpack can compile them into our bundle.js file using the css-loader and style-loader.

The CSS loader takes our css codes and turns it into javascript code.
The style-loader will take the ‘css turned javascript’ code and inject it into the DOM using the style tag.

Loaders are really useful and although it is beyond the scope of this article, I strongly suggest you read up this documentation on loaders and include it in your webpack setup.

I really hope this article was helpful.

--

--

Toyin Olawale
Webtips
Writer for

I write about <code> so I can understand better!