0% found this document useful (0 votes)
18 views8 pages

Web Pack

Webpack is a module bundler that merges multiple JavaScript files and other assets into one or more files to improve the performance of web applications. This document outlines a tutorial for setting up an Angular application using Webpack, detailing prerequisites, installation of dependencies, and the creation of components and modules. It also covers the configuration of TypeScript and Webpack for bundling the application effectively.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

Web Pack

Webpack is a module bundler that merges multiple JavaScript files and other assets into one or more files to improve the performance of web applications. This document outlines a tutorial for setting up an Angular application using Webpack, detailing prerequisites, installation of dependencies, and the creation of components and modules. It also covers the configuration of TypeScript and Webpack for bundling the application effectively.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

What is Webpack

The dynamic web applications usually have lots of javascript files. These files are either created by you or it could be third party
libraries like jquery/bootstrap etc. We include these in our index.html file using <script> tag. When a user sends requests to
our application, the browser requests and loads these files one at a time. If you have lots of these files, then it will make your
application slow. The solution to this problem is to merge all these files into a one or two files so that the browser can download
the entire file in one request. This is where Webpack is used.
Webpack is a powerful module bundler, which scans your web application looking for javascript files and merges them into one
( or more) big file. Webpack has the ability to bundle any kind of file like JavaScript, CSS, SASS, LESS, images, HTML, & fonts
etc. Webpack also comes with Development Server that supports hot module reloading.

Angular Webpack Tutorial


In this tutorial, we are going to build an example application which displays the “Hello and welcome to Angular” with the
logo of Angular below it.
This Tutorial follows the official Angular Webpack guide We have used the codes found in that tutorial and made few changes
where necessary. We also removed the Testing Framework to make it simpler.

Prerequisites
You need to install following before you proceed further with this tutorial

 Visual Studio Code (or any other editor of your choice)


 NPM Package Manager
You can read instruction on how to install from the tutorial Installing and getting started with Angular

Setting up an Angular Application


The Setting up and angular Application requires the following steps

1. Create an Application folder


2. Create package.json configuration file
3. Installing Dependencies
4. Create the Component
5. Create the root module
6. Bootstrap our application
7. Create the index.html
8. Configure our Application
9. Run the application

Create an Application Folder


Open a command prompt and create the folder AngularWebpack.
1
2 md AngularWebpack
3 cd AngularWebpack
4

package.json Configuration file


A package.json file contains the metadata about our application. It includes the list of Javascript libraries that are used by our
application. The NPM package manager reads this file to install/update the libraries.
You can manually create the package.json file and run the command “npm install” to install the dependencies. In this tutorial,
we will show it how to do it from the command prompt.

Run the following command to create the package.json file

1
2 npm init -f
3
Open the Visual Studio code and you can see that the following package.json file in the root folder.

1
2 {
3 "name": "AngualrWebPack",
4 "version": "1.0.0",
5 "description": "",
6 "main": "index.js",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1"
9 },
10 "keywords": [],
11 "author": "",
12 "license": "ISC"
13 }
14

Installing Dependencies
The next step is to download and install Angular & other libraries. We will use NPM package manager to install them.
Installing Angular libraries
Run the following command from the command prompt to install the Angular components.

1
2 npm install @angular/common @angular/compiler @angular/core @angular/forms @angular/http @angular/platform-browser @angular/platform-browser-dynamic @angular/router --save
3
The –save option ensures that these libraries are saved to package.json file

Installing third party libraries


The Angular requires you to install the following dependencies

1
2 npm install core-js rxjs zone.js --save
3
Rxjs or Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable
sequences and LINQ-style query operators. Read the complete tutorial from here
Zone is used for change detection. For more read Zones in Angular
Core-js is a ES6 polyfill for typescript. You can read it from here

Installing Development Dependencies


The development dependencies are those libraries, which required only to develop the application. For Example, javascript
libraries for unit tests, minification, module bundles are required only at the time of development of the application.

Our Angular application needs Typescript. Webpack module, loaders, plugins, and tools for testing the app etc.

Typescript
Typescript is a superset of Javascript. It extends the Javascript and brings options like static typing, classes, interfaces. The
Code written in typescript cannot be used directly in the web browser. It must be compiled to javascript before running in the
web browser. This process is known as Transpiling. The Transpiling is done by Typescript compiler (tsc). Read
Complete Typescript tutorial
1
2 npm install typescript --save-dev
3

Typings
Typescript forces you to define the types before using them. This has great advantages as any errors are detected at the
compile time rather than at the run time.

But our application is going to use a lot of Third Party Javascript libraries in our application. Being written in Javascript, they do
not have types defined in them. The typescript compiler will throw an error as it does not recognize them.

This where type definition files come into play. They provide the type information to these javascript libraries. We need to
download type definition files for each of these libraries. That is done using the typings.

1
2 npm install @types/node @types/jasmine --save-dev
3

Webpack
Webpack along with Webpack dev server can be installed using the following command.

1
2 npm install webpack webpack-dev-server webpack-merge --save-dev
3
The –save-dev option ensures that these are installed as development dependencies

Webpack loaders and plugins


Webpack supports custom loaders and plugins. A loader is a program that allows you to preprocess files as you “load” them.
They extract the content of the file, transform them and then return the transformed content to Webpack for bundling. With the
help of leaders, the Webpack can handle any type of files.
You can read more about loaders from here
Run the following command to install the required Webpack loaders

Webpack loaders
1
2 npm install angular2-template-loader awesome-typescript-loader css-loader file-loader html-loader null-loader raw-loader style-loader to-string-loader --save-dev
3

Webpack plugins
A plugin is a program that changes the behaviour of Webpack

1
2 npm install html-webpack-plugin webpack-merge extract-text-webpack-plugin --save-dev
3

Others dependencies
1
2 npm install rimraf --save-dev
3

Testing tools
1
2 npm install jasmine-core karma karma-chrome-launcher karma-jasmine karma-sourcemap-loader karma-webpack --save-dev
3

Creating the Component


So far we have installed all the required dependencies. The next step is to create our application. Under the root folder of our
application create folder called src. Under src create a folder called app.

Component class
First, let us create an Angular Component. Create app.component.ts under the src/app folder and copy the following code.
1
2 import { Component } from '@angular/core';
3 import '../assets/css/styles.css';
4
5 @Component({
6 selector: 'my-app',
7 templateUrl: './app.component.html',
8 styleUrls: ['./app.component.css']
9 })
10
11 export class AppComponent { }
12
The Component is the most important part of the angular. It controls the region of the screen or View. It consists of three main
parts one is class, a class decorator, and an import statement

Component class
1
2 export class AppComponent { }
3
A component is a simple class. The class is defined using the Export keyword so that it can be used in other parts of the
application. Our component class does not have any methods and properties. The component in real life will have methods and
properties, which supply logic to our view.

@Component decorator
The AppComponent class is then, decorated with @Component decorator attribute. The @Component (called class decorator)
provides Metadata about the component class. The Angular uses this Metadata to create the view

1
2 @Component({
3 selector: 'my-app',
4 templateUrl: './app.component.html',
5 styleUrls: ['./app.component.css']
6 })
7
The Metadata above has three fields. The selector, templateURL & styleUrls

templateUrl
The templateUrl contains the path to the HTML file. The Angular uses this HTML file to render the view. In the above example, it
points to the app.component.html file. Hence we need to create it. Create app.component.html file under the src/app folder
1
2 <main>
3 <h1>Hello from Angular Application with Webpack</h1>
4 <img src="../assets/images/angular.png">
5 </main>
6
styleUrls
The styleUrls is an array of Style Sheets that angular2 uses to style our HTML file. In the above example, it points towards to
app.component.css style sheet. Create a file app.component.css under src/app folder
1
2 main {
3 padding: 1em;
4 font-family: Arial, Helvetica, sans-serif;
5 text-align: center;
6 margin-top: 50px;
7 display: block;
8 }
9

Selector
The selector tells angular, where to display the template. In the example above selector is “’my-app’”. The angular whenever it
encounters the above tag replaces it with the template

Import statement
1
2 import { Component } from '@angular/core';
3 import '../assets/css/styles.css';
4
The import statement is used to import all the libraries that are used in our component class. This statement is similar to C#
using statement. The @Component decorator is available in @angular/core module. Hence we need to refer it in our class. This
is done using the import method as shown above.

Root Module
The Angular follows the modular approach, the application development. Every Angular application must have one module
known as root Module. We will name it as app.module.ts. Create the file with the name app.module.ts under the folder
src/app and add the following code
1
2 import { NgModule } from '@angular/core';
3 import { BrowserModule } from '@angular/platform-browser';
4 import { AppComponent } from './app.component';
5 @NgModule({
6 imports: [
7 BrowserModule
8 ],
9 declarations: [
10 AppComponent
11 ],
12 bootstrap: [ AppComponent ]
13 })
14 export class AppModule { }
15
The Angular module is similar to any other component class we created earlier. Like Component, it consists of three parts.
A class , class decorator and import statement

Module class
1
2 export class AppModule { }
3
Similar to the component, the Module class is defined with the export keyword. Export class ensures that you can use this class
in any other class

1
2 @NgModule decorator
3
We used a @component decorator to define our component. The modules require a @ngModule decorator. @ngModue
decorator passed metadata about the module. & bootstrap. The @ngModule Metadata above has three fields. declarations,
imports & bootstrap.

Imports Metadata tells the angular list of other modules used by this module.
Declaration Metadata lists the components, directives, services etc that are part of this module.
Bootstrap Metadata identifies the root component of the module. When Angular loads the appModule it looks for bootstrap
Metadata and loads all the components listed here. We want our module to AppComponent , hence we have listed it here

Bootstrapping our root module


We have so far created AppComponent which is bound to the HTML template app.component.html. We have added the
AppComponent to AppModule. In AppModule we indicated that the AppComponent is to be loaded when AppModule is loaded

The Next step is to ask the Angular to load the AppModule when the application is loaded. To do need to create main.ts file

Create main.ts in the src folder and copy the following content
1
2 import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 import { enableProdMode } from '@angular/core';
4
5 import { AppModule } from './app/app.module';
6
7 if (process.env.ENV === 'production') {
8 enableProdMode();
9 }
10
11 platformBrowserDynamic().bootstrapModule(AppModule);
12
First, we import platformBrowserDynamic library. This library contains all the functions required to bootstrap the angular
application. Next, we import our AppModule. Finally, we invoke bootstrapModule method of platformBrowserDynamic library to
bootstrap our AppModule

Index page
We need a root page for our application. Create index.html under src folder
1
2 <!DOCTYPE html>
3 <html>
4 <head>
5 <base href="/">
6 <title>Angular With Webpack</title>
7 <meta charset="UTF-8">
8 <meta name="viewport" content="width=device-width, initial-scale=1">
9 </head>
10 <body>
11 <my-app>Loading...</my-app>
12 </body>
13 </html>
14

Assets
We have imported styles.css and used “angular.png” image in our AppComponent.

Create the folder src/assets/css and copy the styles.css to it.


1
2 body {
3 background: #0147A7;
4 color: #fff;
5 }
6
Similarly, create the folder assets/images under src. Download Angular Icon Icon and copy it there.

Configuring Our Application


We have successfully built our application. The next step is to run the application. But before that, we need to configure
Typescript, Typings and Webpack libraries

Typescript
Create the file tsconfig.json in the src folder our project and copy the following
1
2 {
3 "compilerOptions": {
4 "target": "es5",
5 "module": "commonjs",
6 "moduleResolution": "node",
7 "sourceMap": true,
8 "emitDecoratorMetadata": true,
9 "experimentalDecorators": true,
10 "lib": [ "es2015", "dom" ],
11 "noImplicitAny": true,
12 "suppressImplicitAnyIndexErrors": true,
13 "typeRoots": [
14 "../node_modules/@types/"
15 ]
16 },
17 "compileOnSave": true,
18 "exclude": [
19 "node_modules/*",
20 "**/*-aot.ts"
21 ]
22 }
23
You can read https://www.typescriptlang.org/docs/handbook/tsconfig-json.html to learn about each of those compiler options.

Webpack Bundle
The next step is to configure the Webpack. Webpack allows us to bundle all our javascript files into a one or more files. Let us
create three bundles in our application

In the first bundle, we add all our application code like components, service, modules etc. We call it as an app. We do not have
to create a separate file to that. Our main.ts file will be the starting point for this bundle.
We put all the external libraries like Rxjs, Zone etc into a separate bundle. This includes Angular libraries also. Let us call it as
the vendor. To do that we need to create the vendor.ts and import required libraries. Create the file called the vendor.ts
under src folder and copy the following code
1
2 // Angular
3 import '@angular/platform-browser';
4 import '@angular/platform-browser-dynamic';
5 import '@angular/core';
6 import '@angular/common';
7 import '@angular/http';
8 import '@angular/router';
9
10 // RxJS
11 import 'rxjs';
12
13 // Other vendors for example jQuery, Lodash or Bootstrap
14 // You can import js, ts, css, sass, ...
15
In the third bundle, we include the polyfills we require to run Angular applications in most modern browsers. Create a file
called polyfills.ts under the src folder and copy the following code
1
2 import 'core-js/es6';
3 import 'core-js/es7/reflect';
4 require('zone.js/dist/zone');
5
6 if (process.env.ENV === 'production') {
7 // Production
8 } else {
9 // Development and test
10 Error['stackTraceLimit'] = Infinity;
11 require('zone.js/dist/long-stack-trace-zone');
12 }
13

Webpack configuration
The next step is to configure the Webpack.

The Webpack by convention uses the webpack.config.js file to read the configuration information. Create
the webpack.config.js in the root folder of our project. Add the following code
1
2 module.exports = require('./config/webpack.dev.js');
3
The above code tells the Webpack to read the configuration file webpack.dev.js from the config folder.
The Webpack can be setup so that you can have a separate configuration option for testing, development, and production.
What you need to do is to create separate config files for development. testing and production and then switch between this
config file in the main configuration file (webpack.config.js)

Create the folder “config” in the root of our project. This is where we are going to put all over Webpack related configuration
option

Helper functions
Create the file helpers.js under the folder config and copy the following code
1
2 var path = require('path');
3
4 var _root = path.resolve(__dirname, '..');
5
6 function root(args) {
7 args = Array.prototype.slice.call(arguments, 0);
8 return path.join.apply(path, [_root].concat(args));
9 }
10
11 exports.root = root;
12

Common Configurations
Create the file webpack.common.js under the folder config and copy the following code
1
2 var webpack = require('webpack');
3 var HtmlWebpackPlugin = require('html-webpack-plugin');
4 var ExtractTextPlugin = require('extract-text-webpack-plugin');
5 var helpers = require('./helpers');
6
7 module.exports = {
8 entry: {
9 'polyfills': './src/polyfills.ts',
10 'vendor': './src/vendor.ts',
11 'app': './src/main.ts'
12 },
13
14 resolve: {
15 extensions: ['.ts', '.js']
16 },
17
18 module: {
19 rules: [
20 {
21 test: /\.ts$/,
22 loaders: [
23 {
24 loader: 'awesome-typescript-loader',
25 options: { configFileName: helpers.root('src', 'tsconfig.json') }
26 } , 'angular2-template-loader'
27 ]
28 },
29 {
30 test: /\.html$/,
31 loader: 'html-loader'
32 },
33 {
34 test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
35 loader: 'file-loader?name=assets/[name].[hash].[ext]'
36 },
37 {
38 test: /\.css$/,
39 exclude: helpers.root('src', 'app'),
40 loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
41 },
42 {
43 test: /\.css$/,
44 include: helpers.root('src', 'app'),
45 loader: 'raw-loader'
46 }
47 ]
48 },
49
50 plugins: [
51 // Workaround for angular/angular#11580
52 new webpack.ContextReplacementPlugin(
53 // The (\\|\/) piece accounts for path separators in *nix and Windows
54 /angular(\\|\/)core(\\|\/)@angular/,
55 helpers.root('./src'), // location of your src
56 {} // a map of your routes
57 ),
58
59 new webpack.optimize.CommonsChunkPlugin({
60 name: ['app', 'vendor', 'polyfills']
61 }),
62
63 new HtmlWebpackPlugin({
64 template: 'src/index.html'
65 })
66 ]
67 };
68
The webpack.common.js config will contain all the configuration settings, which are common to development, testing, and
production builds.

Now let us look at each part

1
2 entry: {
3 'polyfills': './src/polyfills.ts',
4 'vendor': './src/vendor.ts',
5 'app': './src/main.ts'
6 },
7
First, we let Webpack know our entry points. Remember that we have decided to create three bundles of our application. Our
three entry points are polyfills.ts , vendor.ts, and main.ts all located in the src folder.
The Webpack starts from these files and traverses through it to find dependencies and merges all of them one bundle per each
entry.

1
2 module: {
3 rules: [
4 {
5 test: /\.ts$/,
6 loaders: [
7 {
8 loader: 'awesome-typescript-loader',
9 options: { configFileName: helpers.root('src', 'tsconfig.json') }
10 } , 'angular2-template-loader'
11 ]
12 },
13 {
14 test: /\.html$/,
15 loader: 'html-loader'
16 },
17 {
18 test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
19 loader: 'file-loader?name=assets/[name].[hash].[ext]'
20 },
21 {
22 test: /\.css$/,
23 exclude: helpers.root('src', 'app'),
24 loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
25 },
26 {
27 test: /\.css$/,
28 include: helpers.root('src', 'app'),
29 loader: 'raw-loader'
30 }
31 ]
32 },
33
Webpack then uses leaders to transform our files. For example, the Typescript files (ts extension) are passed through
“angular2-template-loade” and then to “awesome-typescript-loader” (Right to left)
1
2 plugins: [
3 // Workaround for angular/angular#11580
4 new webpack.ContextReplacementPlugin(
5 // The (\\|\/) piece accounts for path separators in *nix and Windows
6 /angular(\\|\/)core(\\|\/)@angular/,
7 helpers.root('./src'), // location of your src
8 {} // a map of your routes
9 ),
10
11 new webpack.optimize.CommonsChunkPlugin({
12 name: ['app', 'vendor', 'polyfills']
13 }),
14
15 new HtmlWebpackPlugin({
16 template: 'src/index.html'
17 })
18 ]
19
The CommonsChunkPlugin removes all the multiple used chunks of code and uses it only once.
The HtmlWebpackPlugin adds a script tag to our index.html for the each of the bundle created.

Development specific configuration


Create webpack.dev.js under the config folder and add the following code
1
2 var webpackMerge = require('webpack-merge');
3 var ExtractTextPlugin = require('extract-text-webpack-plugin');
4 var commonConfig = require('./webpack.common.js');
5 var helpers = require('./helpers');
6
7 module.exports = webpackMerge(commonConfig, {
8 devtool: 'cheap-module-eval-source-map',
9
10 output: {
11 path: helpers.root('dist'),
12 publicPath: '/',
13 filename: '[name].js',
14 chunkFilename: '[id].chunk.js'
15 },
16
17 plugins: [
18 new ExtractTextPlugin('[name].css')
19 ],
20
21 devServer: {
22 historyApiFallback: true,
23 stats: 'minimal'
24 }
25 });
26
The webpack.dev.js file imports the webpack.common.js and uses additional configuration options required only for the
development
1
2 devtool: 'cheap-module-eval-source-map',
3
The devtool defines how the source map is created. The source maps help in debugging our applications in the browser.

1
2 output: {
3 path: path.resolve(rootDir, 'dist'),
4 publicPath: 'http://localhost:8080/',
5 filename: '[name].js',
6 chunkFilename: '[id].chunk.js'
7 },
8
Output configuration has options that affect the output of the Webpack compilation. You can configure location on disk where
the compiled files are written to (path), the name of the bundle (filename), the name of the chunk file (chunkfilename) and
public URL path (publicPath) etc.

1
2 plugins: [
3 new ExtractTextPlugin('[name].css')
4 ],
5
You call any development environment specific plugin here. The extract-text-webpack-plugin removes the compiled CSS
from the bundle and emits is as a separate file.
1
2 devServer: {
3 historyApiFallback: true,
4 stats: 'minimal'
5 }
6
The devServer is used to configure the behavior of web pack-dev-server

Package.json
Finally, Open the package.json and replace the scripts options with the code below

1
2 "scripts": {
3 "start": "webpack-dev-server --inline --progress --port 8080"
4 },
5

Run the Application


From the command prompt type, npm start to run the application. Open the browser and type http://localhost:8080/. You
should be able to see “Hello and welcome to Angular” message on the screen

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy