An Introduction to Webpack

What is Webpack?

Webpack is a bundling tool made from javascript. For instance, It can take up a collection of javascript files and produce a single output javascript file. It can bundle images, css files, javascript files, etc to produce static assets.

Why we need bundling?

Without a module bundler like webpack, one would import packages using html script tags,

<html>
  <head>
    <meta charset="utf-8" />
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.17.20"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>

This type of approach is not advisable since it has few drawbacks.

  • When unused scripts are included, unnecessary code is included.

  • When scripts are included in the wrong order, or if its missed, the application will fail.

  • The packages are imported in the global namespace.

However, if the application code is bundled with webpack, it uses a dependency graph to find out what packages are needed to use in the application and ignores the unused packages. It then uses this dependency graph to generate an optimised and minified bundle which will be executed in the correct order.

Next, a module bundler can compile languages which cannot be understood by the browser like typescript with the use of transpilers like babel.

How to use webpack

npm install webpack webpack-cli --save-dev After adding these to package.json, webpack can be used from command line.

Let's consider an example of using lodash in a project. Let's install lodash from npm.

npm install lodash (A modern JavaScript utility library delivering modularity, performance & extras.)

index.js

import lodash from 'lodash';
import printMe from './print.js'

let value = lodash.join(['a', 'b', 'c'], '~');

console.log(value);
printMe();

Let's have another file named print.js, which exports a function to index.js.

print.js

export default function printMe() {
    console.log('I get called in index.js');
}

Next we setup webpack.config.js file.

webpack.config.js

path module provides utilities for working with file and directory paths

const path = require('path');

module.exports = {
    entry: {
        index: './src/index.js',
    },
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
    },
};

This specifies basically that index.js is our entry file and we want it to be compiled. We also specify that the compiled version be renamed as main.js and placed in subfolder dist, possibly where index.html is also placed.

Now, we shall use webpack from command line,

npx webpack

This will run webpack that is installed in the node_modules folder, starts with the index.js file and finds all require/import statements and replaces them with their appropriate code to create a single output file named main.js inside dist subfolder.

Now this main.js file can be used in index.html file as such,

<script defer src="main.js"></script>

Conclusion

That's webpack in a nutshell. We no longer populate packages in global namespace via external scripts. Any new packages or libraries will be added using require/import as opposed to external scripts.

Note: By default, webpack uses production mode, which will produce minified output file. If you want the output file to be readable to developers, you can use development mode in webpack config file.

const path = require('path');

module.exports = {
    mode: 'development',
    entry: {
        index: './src/index.js',
    },
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
    },
};

Thanks for reading the blog. Feel free to provide inputs and suggestions for any areas of improvement. :)

Check out this guide if you want to learn about loading other assets like css files.