A Brief Introduction to ‘webpack’
If you are in JavaScript application development you might have heard word ”webpack” in recent time. If you have not tried to find out what wabpack is all about? You need to do as soon as possible because there are chances that webpack is more require/beneficiary in your project than you think it should be.
In this post I am going to introduce webpack and its feature with code example so that you can have better understanding, so let’s begin!
Introduction
As per the official webpack website “webpack takes modules with dependencies and generates static assets representing those modules.”
For JavaScript developer have tons of module bundlers available, like grunt,gulp,Browserify etc.
Yet another module bundlers might confuse developer about what is new in webpack that other module bundler cannot do?
In one line answer to this is static asset and code splitting this two are main difference with webpack and other module bundlers we will understand both this in detail with example.
Why we need webpack?
- Do you struggle with initial high loading time of application?
- Do you want all your asset like image, file, third party library etc to be loaded only when you require it (contrast to require.js which only work with js file not static asset like images)
- Do you want to customise every part of module bundle.
Installation
just type following in console,
npm install webpack -gWill do all for you(nodejs is require to install webpack).
How to use webpack?
- Using command line:
- lets assume you have js file called index.js you want to bundle this into bundule.js file.
Just fire up command
webpack ./index.js bundle.jsWebpack will create bundle.js file using index.js, this is very simple example with nothing to load in index.js file,
If index.js file have some other js file as dependency then webpack will also resolve that and all dependency cade will be there inside bundle.js file
Example:
index.js
require(./dependency.js);dependency.js
console.log(“dependency is resolved by webpack”);Now run
webpack ./index.js bundle.jsWhen you execute bundle.js file output will be
“dependency is resolved by webpack”Similarly we can require .css file also, but need to tell about web pack to use loader for css
webpack ./index.js bundle.js --module-bind ‘css=style-loader!css-loader’- Here ‘ ! ‘ used as chaining the loader.
- css-loader - resolve url inside require to get file.
- style -loader - insert css file to where require is used.
Now inside html/js we can use require to load css file and webpack will take care of everything.
As you can see this command line is not useful if we have more number of js file and multiple module to load, solution to this is config file for webpack.
2. Webpack config file:
Config file name in your project should be webpack.config.js
Let’s have simple config file:
module.exports = {
entry: "./index.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
rules: [{
test: /\.css$/,
use: [{
"Style-loader",
"css-loader"
}]
}]
}
};Note that this is latest webpack v2 syntax , webpack v1 have slightly different syntax than this.
Inside ‘use’ block we can chain loader like mention in this config file using ’ , ‘only.
Now let’s talk about features of webpack with example:
- Module loading commonjs and AMD
Module is chunk of code which is written in different file to keep them separate and load only when some other code require it.
If you are familiar with c language than,
#include “file”is kind of module loading.
If you are familiar with java then,
import java.util.*;Is close enough to module loading
Javascript don’t provide module loading by default (ES6 standrd provides but not implemented in morden browser)
There are third party module loader available in js like AMD and commonjs
webpack supports both AMD and CommonJs module styles.
2. Plugins interface:
webpack has a rich plugin interface. Most of the features are internal plugins using this interface. This makes webpack very flexible
More on plugins here.
3. Loader introduction with small example:
If you want some pre-processing in file before you require on application(for example converting .less file to .css file) this task can easily be done vai loaders in wabpack, there are several popular loader available in webpack still if you want You can easily write your own loaders running in Node.js.
4. Code splitting:
This is very interesting and useful feature of webpack, let’s try to understand this.
Let’s say you have big application with good number of js file and application also depends on loads of third party library like jquery, lodash etc.
In ideal way of thinking, your build should contain one bundle.js file in your html, this bundle.js contain all JavaScript code including JavaScript code of third party library if you have not used cdn for that.
But this can be problematic if bundle.js file is very large and also we can not use caching for this as single change in file will trigger to load entire bundle.js file
To load application fast at start and load other js code async webpack provide code splitting
There are two way to split your code into chunks:
- As of webpack v2 import() module loading syntax proposal is on the way into ECMAScript.
2. Code Splitting — Using require.ensure()
- require.ensure() inside code will act as split point for webpack, webpack create separate file for this and it will be loaded on demand using jsonp request.
To understand this in detail let’s take example from webpack official web site
Let’s assume we have three javascript file
Entry.js
require(‘./a’);
require.ensure([], function(require){
require(‘./b’);
});a.js
console.log(‘***** I AM a *****’);b.js
console.log(‘***** I AM b *****’);On running webpack on this project, we find that webpack has created two new bundles, bundle.js and 0.bundle.js.
entry.js and a.js are bundled in bundle.js.
b.js is bundled in 0.bundle.js.
Third party library(vender file) are not going to change for application, if we can split it and it will be in separate file which will be cache by browser and it will not be re-download every time we reload app.
This can be done using CommonsChunkPlugin in webpack
Learn more about CommonsChunkPlugin from here
5. Optimisation
You can optimise your code(both css and js) using plugins like uglify.
Some of important plugins are,
webpack.optimize.UglifyJsPlugin() - for Minification.
webpack.optimize.DedupePlugin() - for removal of duplicate code.
6. Multiple target:
webpack’s main target is the web, but it also supports generating bundles for WebWorkers and Node.js.
7. Development tool :
If you want to debug your code webpack supports SourceUrls and SourceMaps for simple debugging
Source map allow you to see the point in your code where error has accured in your dev tool.
8. Development server:
Webpack also provide solution to start web server on application
It provide live reloading
npm install webpack-dev-server -gAfter installation of dev server just type
webpack-dev-server — openIt will start development server on http://localhost:8080 and now you are good to go for coding!
Official webpack website https://webpack.js.org/
NOTES:
- If your application is small with single javascript file then webpack might not require for you.
- production you will not find any module loader kind of thing webpack replace this code with code that browser or node.js understand.
- “webpack v1 is deprecated. We encourage all developers to upgrade to webpack 2” this is official statement from webpack that all developer should either use webpack v2 or migrate to v2 from v1.
