Webpack 4.30 Tutorial for Beginners 🚀🚀🚀

Webpack 4.30 Tutorial for Beginners 🚀🚀🚀

Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging. In this tutorial you will learn Webpack 4.30 from the basics to advanced!

Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging. In this tutorial you will learn Webpack 4.30 from the basics to advanced!

Nowadays, we’re forced to use many accessory tools to facilitate, speed up and optimize our web development workflow. Often though, such tools add an extra layer of complexity into the stack. As a result, we need to utilize additional time and effort to learn, understand and use these tools correctly. The same is true for webpack.

When using Webpack 4.30 for the first time, it can be difficult to understand how it works and how it should be used. Although it has good documentation, it can be daunting for novices, and it has a steep learning curve. However, webpack is worth learning and can save considerable time and effort in the long run. In this tutorial, I’ll introduce all the core concepts to help you get started.

What Is Webpack?

As its core, webpack is a static module bundler. In a particular project, webpack treats all files and assets as modules. Under the hood, it relies on a dependency graph. A dependency graph describes how modules relate to each other using the references (require and import statements) between files. In this way, webpack statically traverses all modules to build the graph, and uses it to generate a single bundle (or several bundles) — a JavaScript file containing the code from all modules combined in the correct order. “Statically” means that, when webpack builds its dependency graph, it doesn’t execute the source code but stitches modules and their dependencies together into a bundle. This can then be included in your HTML files.

Now, to expand the above cursory overview, let’s explore the main concepts webpack uses.

Webpack Main Concepts

Webpack has some main concepts which we need to understand clearly before digging in its practical implementation. Let’s examine them one by one:

  • Entry. The entry point is the module, which webpack uses to start building its internal dependency graph. From there, it determines which other modules and libraries that entry point depends on (directly and indirectly) and includes them in the graph until no dependency is left. By default, the entry property is set to ./src/index.js, but we can specify a different module (or even multiple modules) in the webpack configuration file.
  • Output. The output property instructs webpack where to emit the bundle(s) and what name to use for that file(s). The default value for this property is ./dist/main.js for the main bundle and ./dist for other generated files — such as images, for example. Of course, we can specify different values in the configuration depending on our needs.
  • Loaders. By default, webpack only understands JavaScript and JSON files. To process other types of files and convert them into valid modules, webpack uses loaders. Loaders transform the source code of non-JavaScript modules, allowing us to preprocess those files before they’re added to the dependency graph. For example, a loader can transform files from a CoffeeScript language to JavaScript or inline images to data URLs. With loaders we can even import CSS files directly from our JavaScript modules.
  • Plugins. Plugins are used for any other task that loaders can’t do. They provide us with a wide range of solutions about asset management, bundle minimization and optimization, and so on.
  • Mode. Typically, when we develop our application we work with two types of source code — one for the development build and one for the production build. Webpack allows us to set which one we want to be produced by changing the mode parameter to development, production or none. This allows webpack to use built-in optimizations corresponding to each environment. The default value is production. The none mode means that there won’t be used any default optimization options. To learn more about the options webpack uses in development and production mode, visit the mode configuration page.
How Webpack Works

In this section we’ll examine how webpack works. Even a simple project contains HTML, CSS and JavaScript files. Also, it can contains assets such as fonts, images, and so on. So, a typical webpack workflow would include setting up an index.html file with the appropriate CSS and JS links, and the necessary assets. Also, if you have many CSS and JS modules which depend on each other, they need to be optimized and properly combined in one unit ready for production.

To do all this, webpack relies on configuration. Although webpack 4 comes with reasonable defaults, for any non-trivial project you’ll need to provide a special configuration file webpack.config.js, which describes how the files and assets should be transformed and what kind of output should be generated. This file can quickly become quite monolithic, which makes it hard to understand how webpack does its job unless you know the main concepts behind its working.

Based on the provided configuration, webpack starts from the entry points and resolves each module it encounters while constructing the dependency graph. If a module contains dependencies, the process is performed recursively against each dependency until the traversal has completed. Then webpack bundles all project’s modules into a small number of bundles — usually, just one — to be loaded by the browser.

Getting Started with Webpack 4.30

Note: you can find the files for our project in the GitHub repo.

Now that we have solid theoretical foundation, let’s implement it in practice.

To start, we’ll create a new directory and switch to it. Then we’ll initialize a new project:

mkdir learn-webpack
cd learn-webpack
npm init -y

Next, we need to install webpack and webpack CLI locally:

npm install webpack webpack-cli --save-dev 

Now, the content of the generated package.json should be similar to the following:

  "name": "learn_webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.0"

Besides bundling modules, webpack can be used as a simple task runner. We can create webpack tasks by including the name of our task followed by its instructions in the scripts section of the package,json file. Let’s try this now. Open package.json and change the scripts object to the following:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "webpack --mode development",
  "build": "webpack --mode production"

Within the scripts property, webpack allows us to reference locally installed npm packages by their names. We use that and the --mode flag to define dev and build tasks, which will run webpack in development (npm run dev) and production (npm run build) mode respectively.

Before we test the tasks we’ve just created, let’s create a src directory and put an index.js file in it so that it contains console.log("Hello webpack");. Now we can already to run the dev task to start webpack in development mode:

$ npm run dev

> [email protected] dev C:\Users\User\Webpack\learn_webpack
> webpack --mode development

Hash: 5bb3bdc1efd7b7f4b627
Version: webpack 4.30.0
Time: 226ms
Built at: 2019-04-16 17:48:32
  Asset     Size  Chunks             Chunk Names
main.js  3.8 KiB    main  [emitted]  main
Entrypoint main = main.js
[./src/index.js] 27 bytes {main} [built]

Great! It works as expected. But to verify that we get the correct output, we need to display the result in the browser. To do that, let’s create an index.html file in the dist directory:

    Getting Started

Now, if we open the file in the browser, we should see the Hello webpack message in the console.

So far, so good. But writing our index.html file manually can be problematic in some cases. For example, if we change the name of our entry point, the generated bundle will be renamed, but our index.html file will still reference the old name. So, we’ll need to update our HTML file manually every time we rename an entry point or add new one. Fortunately, we can easily fix that with the html-webpack-plugin. Let’s install it now:

npm install html-webpack-plugin --save-dev 

At this point, to activate the plugin, we need to create a webpack.config.js file in the root directory with the following content:

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      title: "Webpack Output",

As you can see, to activate a webpack plugin, we need to include it and then add it to the plugins array. If needed, we also pass options to the plugin.

Let’s run our build now to see what will happen:

$ npm run build

> [email protected] build C:\Users\User\Webpack\learn_webpack
> webpack --mode production

Hash: e56a796f5ccfebcc8270
Version: webpack 4.30.0
Time: 1088ms
Built at: 2019-04-16 20:44:47
    Asset       Size  Chunks             Chunk Names
index.html  183 bytes          [emitted]
  main.js  956 bytes       0  [emitted]  main
Entrypoint main = main.js
[0] ./src/index.js 27 bytes {0} [built]
Child html-webpack-plugin for "index.html":
    1 asset
    Entrypoint undefined = index.html
    [2] (webpack)/buildin/global.js 472 bytes {0} [built]
    [3] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 2 hidden modules

Let’s open the index.html. As we can see, the plugin automatically creates an updated index.html file for us which uses the title option from the configuration:

    Webpack Output

Let’s now expand our project and specify custom names for the entry and output properties. In webpack.config.js we add the following before the plugins property:

entry: './src/app.js',
output: {
  filename: '[name].bundle.js',
  path: path.resolve(__dirname, 'dist')

Now, we’ll create an src/component.js file:

export default (text = "Hello webpack") => {
  const element = document.createElement("p");

  element.innerHTML = text;

  return element;

Next, we rename index.js to app.js to reflect our changes, and swap its content with the following:

import component from "./component";


Now, let’s run webpack in production mode:

$ npm run build

> [email protected] build C:\Users\User\Webpack\learn_webpack
> webpack --mode production

Hash: 9f78936f8a2a21061f0b
Version: webpack 4.30.0
Time: 1689ms
Built at: 2019-04-17 23:43:40
        Asset       Size  Chunks             Chunk Names
    index.html  190 bytes          [emitted]
main.bundle.js   1.04 KiB       0  [emitted]  main
Entrypoint main = main.bundle.js
[0] ./src/app.js + 1 modules 227 bytes {0} [built]
    | ./src/app.js 79 bytes [built]
    | ./src/component.js 148 bytes [built]
Child html-webpack-plugin for "index.html":
    1 asset
    Entrypoint undefined = index.html
    [2] (webpack)/buildin/global.js 472 bytes {0} [built]
    [3] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 2 hidden modules

Let’s examine and clarify the information from the webpack output. Beginning from the top, we see the hash of the build, webpack version, and the time it took to execute the build. Next, we see the files generated in the dist directory (index.html and main.bundle.js). Below them, we see the entry module (app.js) and its dependency (component.js). The output after Child html-webpack-plugin for "index.html": is related to the internal work of the html-webpack-plugin and we can safely ignore it.

So now, in the dist folder, we have the newly generated bundle file main.bundle.js. If we open index.html in the browser, we should see Hello webpack displayed on the page. Also, if we check the source of index.html, we’ll see that the value of the src property in the script tag is updated to main.bundle.js.

Working with Scripts

In this section, we’ll discover how ES6 can be transpiled to ES5-compliant code which works in all browsers. Let’s start by running the following command:

npm run dev -- --devtools false

Next, let’s open main.bundle.js:

/***/ "./src/component.js":
  !*** ./src/component.js ***!
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony default export */ __webpack_exports__["default"] = ((text = "Hello webpack") => {
  const element = document.createElement("p");

  element.innerHTML = text;

  return element;

/***/ })

As you can see, the modern ES6 features (the arrow function and the const declaration) from component.js module are not transformed to ES5-compliant code by default. To make our code work in older browsers, we must add the Babel loader:

npm install babel-loader @babel/core @babel/preset-env --save-dev 

Then, in webpack.config.js add module after the output property:

module: {
  rules: [
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']

When we define rules for a webpack loader, there are usually three main properties we need to define:

  • test, which describes what kind of files should be transformed.
  • exclude, which defines the files which should not be processed from the loader(s), if we have such.
  • use, which tells which loader(s) should be used against the matched modules.

Run the following command again:

npm run dev -- --devtools false 

This time, the code in main.bundle.js is compiled:

/***/ "./src/component.js":
  !*** ./src/component.js ***!
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony default export */ __webpack_exports__["default"] = (function () {
  var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "Hello webpack";
  var element = document.createElement("p");
  element.innerHTML = text;
  return element;

/***/ })

Perfect. Now we can use the modern JS features, and webpack will transform our code so it can be executed by older browsers.

Working with Styles

In this section, we’ll see how we can add some styles to our project. To do this, we need to install two loaders:

npm install css-loader style-loader --save-dev 

css-loader parses the CSS into JavaScript and resolves any dependencies, style-loader outputs our CSS into a `` tag in the HTML document.

Let’s add the necessary configuration in webpack.config.js:

  test: /\.css$/,
  use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],

Here, the order of loaders is important. They’re evaluated in reverse order — that is, from right to left and from bottom to top.

Now, let’s create a file src/style.css:

p {
  color: red;

Then we import it into app.js:

import './style.css' 

When we run webpack and then open the index.html, we should see the Hello webpack message in red.

Asset Management

Most often your project will contain assets such as images, fonts, and so on. Here we’ll explore an example with images. First, we’ll need to install a file loader:

npm install file-loader --save-dev 

Next, we’ll add new rule in the webpack.config.js:

  test: /\.(png|jpg|gif)$/,
  use: [
      loader: 'file-loader'

Now, to test the loader we’ll create an image-component.js file, in the src directory, with the following content:

import image from "./image.png"

const img = document.createElement("img")
img.src = image

Here, we import our image as a module and use it to create an `` tag. We need to put that image in the src directory.

The next thing is to import our image component in app.js:

import './image-component' 

And voila. Now, when we run webpack and open the page, we should see the image above the Hello webpack message.

Speed Up the Development Process with webpack-dev-server

Currently, we need to rebuild our code every time we make a change. Fortunately, webpack offers a live-reloading web server which automatically builds and refreshes the page. To install it:

npm install webpack-dev-server --save-dev 

We need to update our dev script, in package.json, to use the server:

"dev": "webpack-dev-server --mode development" 

Now let’s configure the server in webpack.config.js by adding the following property:

devServer: {
  contentBase: './dist',
  open: true

This tells webpack-dev-server to serve the files from the dist directory and to open the entry page automatically.

Now, if we run webpack (npm run dev), we should see how the page is automatically opened in the browser on localhost:8080:

i 「wds」: Project is running at http://localhost:8080/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from ./dist

If we now change any of the source files and save them, the web server will automatically reload the page after the code has been compiled. Try to change the color property in our CSS file to green, for example, and you should see how the color is updated appropriately in the page.

Clean Up the Output

As our project progress, the dist folder might become quite cluttered. On every build, webpack will generate the bundles and put them in the dist folder, but it doesn’t keep track of which files are actually in use by your project. So it’s good practice to clean the dist folder before each build, so that only the files in use will be generated. To do this, we need to install and configure the clean-webpack-plugin:

npm install --save-dev clean-webpack-plugin 

In webpack.config.js:

const CleanWebpackPlugin = require('clean-webpack-plugin');


plugins: [
  new CleanWebpackPlugin()

Now, run webpack (npm run build) and inspect the dist folder. You should now only see the files generated from the build without old and unused files. In our case, the file which should be deleted is main.js.


Webpack is a useful and powerful tool. This tutorial introduces only the core concepts, but webpack offers many more features, plugins, and different techniques to apply them, which you can adopt as your knowledge grows.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:


First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?


I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI

Top Web Application Developer

Top Web Application Developer

You can also contact a web application development company for your business but then why not to contact the best web application development company that can turn up your business and customer satisfaction ratio to sky touching heights.

Not long-ago internet came into existence and the world has never been the same ever since. The Internet made sure that people and business do evolve at a faster rate than ever and was never merciful to the slow ones. Because of this competition and availability of any business with few clicks made India one of the hubs as IT center. This trend of constantly updating has given rise to smartphones, smart machines, wearable gadgets and a lot more is yet to come in the upcoming years. In such time it is always a good idea to hire Web App Developer from India at your service. They are expert in developing not only websites but web applications as well.

We at HireFullStackDeveloperIndia, have a huge team of experienced developers that have grasped over different domains in front and back end development. You can hire web app developers in India from us with many advantages that you won’t get anywhere else in the industry.

Here is why we are the best option if you are looking forward to hiring web app developers in India:

  • Flexible hiring models available, as per your convenience and requirement
  • Maximum ROI, compared to any other company or team of developers.
  • We provide you with Source code Authorization meaning code written for you belong only to you. It cannot be used or copied anywhere else.
  • All of our developers are sound with agile development methodology, so you will be in a constant loop of suggestions, ideas, trends, and updates about your project.
  • Our developers are good with creating custom web applications as well; it guarantees you a better product without any compromise of non-existing functionalities.
  • You can save huge costing on infrastructure by utilizing our hire web app developer in India program.
  • Your hired developer or team will be easily accessible to your preferred mode of communication.
  • You get to exercise complete control over your team or individual that you hire.
  • We believe in Integrity and Transparency.
  • Our developers are highly creative and motivated to deliver excellence.

HireFullStackDeveloperIndia is a Web Application Development Company in India that is known worldwide for our Innovative guaranteed solutions. You can inquire with us about your project and we will be providing you multiple suitable developers that are the best fit for your requirements. You can evaluate them and select one or multiple whosoever deems fit to you. After this, all you have to do is provide your valuable input to the resource through sprint base project development until you get delivery of your project.

Our engagement model will also allow you to get our development team to your site location and proceed with development from your premises.