Do you want your JavaScript code to be in order? Get familiar with Webpack!

What is Webpack?

Webpack is a tool that helps with dividing code into modules. It allows you to easily manage dependencies. As a result, the developer can treat the application as the collection of independent modules that later will be compiled and delivered to the browser.
Main assumptions of Webpack:

  • maintaining a short loading time of website (especially important for large projects);
  • dividing the dependencies into small parts, which can later be loaded on demand;
  • easy configuration of virtually any part of the tool.

How it works?

Webpack is responsible for capturing dependencies in the project and creating static code-including packages ready to upload on demand.

Main elements of Webpack :

  • loaders – used for preprocessing files. They allow to merge static resources. It is possible to add custom loaders written in Node.js;
  • code splitting – allows to divide the code into many parts for later asynchronic loading while application is running;
  • optimization – optimization is a crucial element of WebPack. It allows to reduce the size of JavaScript file via minification. It adapts files for cache updates with the usage of hashes.

Basic commands

webpack

Executes everything that is included in the config file. Creates a version of files that are later used by developers

webpack -p

Works similarly to webpack command with one difference – it builds a package that is ready to use in production environment.

webpack -watch

This command builts a project after each modification.

webpack-dev-server

Serves files from the current folder

Installation

Webpack is installed via npm (Node Package Manager). In order to start using WebPack you have to:

  • install WebPack globally:

npm install webpack -g

  • create package.json file:

npm init

  • add webpack to package.json dependencies’ file:

npm install webpack -- save-dev

  • create configuration file (webpack.config.js), for instance:

module.exports = { entry: './file.js', output: { path: __dirname, filename: 'bundle.js' } };

After all these instructions Webpack is ready to use.

Examples

Let’s create a simple project which will build the application and serve it via the local IP:

  1. Create a folder where the application will be stored and execute steps described in the previous section about installing Webpack;
  2. Create index.html with the empty template of the website;
  3. Using the <script src="bundle.js"></script> line, add bundle.js to the recently created index.html file:
  4. Create styles.css and add styling for testing, for instance:
    body {
    background-color: #d97d34
    }
  5. Add the JavaScript file content.js, where you have to include:
    function Content() {
    console.log('merix');
    }
    module.exports = Content;
  6. Add main.js, where we will later insert dependencies and type:
    require("./style.css");
    var Content = require("./content.js");
    var content = new Content();
  7. Change the content of webpack.config.js to:
    var OpenBrowserPlugin = require('open-browser-webpack-plugin');
    module.exports = {
    entry: "./main.js",
    output: {
    path: __dirname,
    filename: "bundle.js"
    },
    module: {
    loaders: [{
    test: /\.css$/,
    loader: "style!css"
    }]
    },
    plugins: [
    new OpenBrowserPlugin({
    url: 'http://localhost:8080'
    })
    ]
    };
  8. Install open-browser-webpack-plugin module, which is automatically running the built application in the browser:
    npm install open-browser-webpack-plugin --save-dev
  9. Launch the console in the project’s folder and type:
    webpack-dev-server

Alternative tools:

Gulp and Grunt

The most popular tools capable of substituting for Webpack are, above all, gulp and grunt which were described in one of our previous articles: “Gulp.js – what is that all about?”.

Browserify

Browserify allows to use CommonJS modules in the browser. Dependencies are defined by the developer and Browserfiy takes care of the rest – it groups and merges them into one JavaScript file.
Defining the dependencies in the project is based on using require(‘.yourJsFile.js’). You can add modules from node_modules downloaded via npm in the same way.

RequireJS

This tool uses JavaScript which is responsible for loading modules. This framework was created with the idea of using it for the browsers, but it can be successfully used in other environments (for instance Node.js). RequireJS greatly reduces the loading time of the website and increases the quality of the code.

RequireJSBrowserifyWebpackPreprocessingYESYESYESMinificationYESYESYESUpload of packages on demandYESNOYESRAM-heavyNOYESYESPluginsYESYESYES

Summary

Webpack is an excellent tool for managing dependencies and grouping them into modules- it has an easy configuration and works really quickly. Webpack makes it really easy to integrate different standards for defining modules or to compile other languages (eg. TypeScript) to JavaScript.It’s focused on browsers, but it can also be used for other areas as well. Webpack is great for every developer as it simplifies their work - I highly recommend using it.

Navigate the changing IT landscape

Some highlighted content that we want to draw attention to to link to our other resources. It usually contains a link .