Webpack in Angular2

Ahteshamax
Posted by in Angular 2 category on for Beginner level | Points: 250 | Views : 1665 red flag

In this article we will explain Webpack in Angular 2.

Webpack is an open source JavaScript framework especially for module bundling, in short Webpack is a module bundler. When working with web application project you would be creating lots of JavaScript(.js) files, CSharp(.cs) files, html files and images files like jpg, png etc. And in project these created files may be dependent on each other to complete project task.With many such small individual dependent components or files with which a web application is composed of we cannot go on server to publish web application. It will lead to handling issue with all individual files or components when hosting on server. In order to get rid of it Webpackis one of the solutions for it where all the individual dependent files are bundled together. These bundling are done by looking at dependencies of files on each other and Webpack creates static asset out of it which avoids rather than dealing with many files with a single bundle.


Understanding Webpack with example

Let us try to understand with the help of small practical example and its demonstration. Consider the following image where we have Customer.js, Address.js and Phone.js. Here Customer can have multiple addresses, Customer’s addresses can have multiple Phone numbers so in short Customer is dependent on Address and Address is dependent on Phone.


Now all these single Customer.js, Address.js and Phone.js file will be bundled into single file using Webpack. Before bundling it Webpack will check for dependencies and then bundling will be done accordingly.


In order to do this practical sample we have used Visual Studio Code in this article. For that go the project folder and then open three new notepads save it withTypeScript(.ts) extension with name Customer.ts, Address.ts and Phone.ts. Now open each .ts file one by one and write the below mentioned code respective in each .ts file.

For Customer.ts below is the code
import {Address} from "./Address"

class Customer{
a: Address = new Address(); 
Addresses: Array
= new Array
(); }

First line of the code is to get“Address” file which is available in the project folder. Next is to create class “Customer” and first create variable “a” and then under it create Array “Address” to store multiple addresses.

For Address.ts below is the code
import {Phone} from "./Phone"

export class Address{
b: Phone = new Phone();
Phones: Array = new Array();
}
Similarly in “Address.ts” file import “Phone.ts” file. Then create class “Address” and mark it export so that it can be imported easily in the “Address.ts”file. Under class “Address” create variable “b” then create Array “Phone” so that multiple phones can be stored.
For Phone.ts below is the code
export class Phone{

}
Finally create class Phone mark it as export as it will be used in “Address.ts” file


Once the (.ts)files are created next is to Build the project at the end this TypeScript(.ts) will converted to JavaScript (.js). To “Build” the project, press “ctrl+shift+B” on the keyboard. If you see this mark “/” at the bottom revolving then it means project “Build” is processing as shown in the image below.


Or in case if you see error on top of “No task runner configured” when clicked on ctrl+shift+B then configure it by clicking on the button “Configure Task Runner” available at the right as shown in the image down below


Select Task Runner as “Grunt” which will create .vscode folder under that tasks.json file will be created.


Next is to configure “tasks.json” fileby doing the following changes into it so that it can be used to “Build” the project.

Default state of tasks.json fileModified state of tasks.json file
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "grunt",
    "isShellCommand": true,
    "args": ["—no-color"],
    "showOutput": "always"
}
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "args": ["-p","."],
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}

After “tasks.json” file is configured you will now be able to “Build” the project.


After successful “Build” is created it means that project is running proper at the client side. And also it will create .js and .map file for each .ts file within “wwwroot” folder. So three simple files now have created after compiling six more files. If these project files now gets published or hosted on the server directly will have to work individually on each files as each of them are dependent on each other. This will lead to huge file management issue to tackle this situation. It would be very much helpful if all these individual files gets single bundled which exactly Webpack does for us.


Working of Webpack

As the name says Webpack,it packs alllogically dependent multiple web files into single bundled JavaScript file under the web development environment. So the next question arises that how does Webpack comes to know about which files is dependent on whom? Dependency of the modules can be defined by any JavaScript modular specification like common.js, (Asynchronous Module Definition)AMD or (Universal Module Definition)UMD.

Here inorderto identify the dependencies we have used common.js specification in our project. This common.js specification gets available in the .js file which is generated when compilation of .ts file is done along with .map file.If you browse folderwise, then this .js file is located in the project folder of “Webpack”. So the path to get this file is Webpack > wwwroot > compiled-js.

Similarly under VS code you can get these .js files just by expanding the project folder. When these .js files are opened under VS code you will find two keywords “exports”and “require” and by looking at these keywords Webpack decide dependencies where “export” is exportsvariable and “require” is used by the consuming class. When Webpack works it checks for the first file on the web page which gets loaded which is “Customer.js” and internally it is dependent on “Address.js” and finally when Webpack goes to “Address.js” it is gets “require” keyword which means it dependent on “Phone.js” as shown in the image down below. In this way dependencies are identified by Webpack and then one bundled .js file is created.


Installing Webpack in project

Installing Webpack is also going to be same likewise we do installation. Let us repeat incase if you do not remember go to Start Menu program search for “node.js” and click on “Node.js command prompt” as shown in the image down below. Once clicked on it will open command prompt window on that type the following command “npm install –g webpack” with this installation process of Webpack will initiate and complete the installation successfully.


After the Webpack is installed next step is to create a single bundle pack of three interdependent .js file.

For that on the command prompt change default path “c:” to project path “e:” here is the complete link of the path with the command to change drive

“cd E:\Webpack\Webpack\wwwroot\compiled-js”

Once the path is changed next we have to give the starting .js file name i.e. “Customer.js” with which Webpack can go and start identifying the dependencies on the basis of “require” and “export”. To create single bundle file from individual .js file, here is the command

“webpack "Customer.js" "SingleBundle.js"”

Where “Customer.js” is the starting .js file where “Webpack” will start with and the name of the single generated .js file by Webpack is “SingleBundle.js”.

After the command is written press enter and wait for a while till the time Webpack complete its work of converting individual .js file to single bundle .js file. Once Webpack completes its execution you will see the successful message on command prompt as shown in the image down below.


You can also go and check it under VS code for newly created .js file with name “SingleBundle.js”.

Please note: If you do not see newly created .js file then click on refresh to see the file under Explorer

After you click on the single bundle file which we have named “SingleBundle.js” under this you will see all the three individual files bundled together as shown in the image down below.

By doing this with single bundling all the files our deployment life becomes very easy.


Using Webpack in production

Webpack production is also done in similar way just by using text in the command with “–p” after writing webpack keyword then followed by first name of individual .js file i.e. “Customer.js” with which Webpack will start bundling file following dependency of each file and create bundle with name “SingleBundle.js”.


Now under VS code if you see then you will find that “SingleBundle.js” is compressed by removing all comments and other not necessary part from it. And by looking to the following image you will find that file is compressed and only the important required part for the production is now available.


Modular approach

In real world projects are not going to simpler there would be many modules under one project. Then how to handle such situation where we have multiple modules consider the following scenario diagram where we have two modules one is of “Customer” and while other is “Invoice” module. And also their bundling needs to be done separately for both”.

Below is the image screenshot which shows two modules Customer Module and Invoice Module, each module has individual .js also they dependency on each other.


Next using Webpackwe will create two separate bundles one named “CustomerBundle.js” and other bundle is named as “InvoiceBundle.js. So how to create two separate bundles for each module in a single command of “webpack” on command prompt.

Answer to this is by creating config.json file with which we can resolve this issue. Below is the image which shows config file created for two bundles with name “webpack.config.json” in the project folder.

There are three parameters which need to be set for each bundle. First provide “name”, then “entry” location where the .js file is located and finally “output” where we have to give suitable file name to the bundle.


Once the config file is created now it will be very easy to create two separate bundle files using Webpack. Same steps we have to follow as we did earlier to create bundle. Go to node.js command prompt and execute the “webpack.config.json” file from the project folder where this .json file is created and saved.

Following is the command which will be used on command prompt and press enter

E:\Webpack\Webpack>webpack

After the command is executed you will see two separate bundles created one for “CustomerBundle.js” and other is “InvoiceBundle.js”. Under “CustomerBundle.js” it will have “Address.js”, “Phone.js” and “Customer.js” individual files. While under “InvoiceBundle.js” it will bundle “InvoiceItem.js”, “Tax.js”, and “Invoice.js”.


With the help of Webpackworking on module approach to create bundle makes life very easy to go to production.

Hope that above article on Webpack is clearly understood by the reader. Suggesting reader if you are new learner then go through below video on step by step Angular2: -

Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Posted by: Contomlon on: 4/4/2017 | Points: 25
I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.

Login to post response

Comment using Facebook(Author doesn't get notification)