Everything you need to know about Webpack

It’s bit difficult to use webpack for the first time. Btw webapack has very good documentation. 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’s Webpack?

In a nutshell webpack is a static module bundler. In a project webpack can treat all files and assets as modules. 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.

Webpack main concepts

Webpack has some main concepts which you 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.

How webpack works

Even a simple web projects has a html, css and js contents. 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.

Chamod Shehanka a FullStack Developer at Platformer and Writer at Noteworthy, Platformer and The Java Report