Published: April 24 2019

Angular 7 Tutorial Part 2 - Create Base Project Structure & Webpack Config

Other parts available in Angular 7 tutorial series:


Angular 7 Tutorial Part 2

In part 2 of this Angular 7 tutorial series we're going to setup the base project structure and webpack config for an Angular 7 application.

The complete source code for this part of the tutorial is available on github at https://github.com/cornflourblue/angular-7-tutorial in the part-2 folder.

Steps:

  1. Create project folder
  2. Create package.json
  3. Install Angular 7 Dependencies
  4. Install Angular 7 Dev Dependencies
  5. Create tsconfig.json
  6. Create webpack.config.js
  7. Create src folder
  8. Create app folder
  9. Create Angular App Component template
  10. Create Angular App Component
  11. Create Angular App Module
  12. Create Angular 7 Polyfills File
  13. Create Angular 7 Main (Bootstrap/Launch) File
  14. Create Angular 7 Main Index Html File
  15. Add start script to package.json
  16. Start Angular 7 Application!


Create project folder

You can name it anything you like, I called mine angular-7-tutorial, then open the folder in Visual Studio Code. This might seem like an obvious step but I decided to include every detail of the process from the beginning.


Create package.json

Inside the project folder create a file named package.json. This file contains project configuration information including package dependencies which get installed when you run npm install. More info available at https://docs.npmjs.com/files/package.json.

Open package.json in VS Code, set the name property to the same as the project folder name and set the version property to 1.0.0. It should look something like this:

{
    "name": "angular-7-tutorial",
    "version": "1.0.0"
}


Install Angular 7 Dependencies

Run the following command from the project folder to install and save the npm packages required to run Angular 7 applications:

npm install -save @angular/common@7 @angular/compiler@7 @angular/core@7 @angular/forms@7 @angular/platform-browser@7 @angular/platform-browser-dynamic@7 @angular/router@7 core-js@3 rxjs@6 zone.js@0

The command will download the packages into a node_modules folder and add them to the dependencies property in the package.json file. So next time to install all of the packages you just need to run npm install and it will use the list in package.json.

The package.json should look like this after installing Angular 7 dependencies with the above command:

{
    "name": "angular-7-tutorial",
    "version": "1.0.0",
    "dependencies": {
        "@angular/common": "^7.2.13",
        "@angular/compiler": "^7.2.13",
        "@angular/core": "^7.2.13",
        "@angular/forms": "^7.2.13",
        "@angular/platform-browser": "^7.2.13",
        "@angular/platform-browser-dynamic": "^7.2.13",
        "@angular/router": "^7.2.13",
        "core-js": "^3.0.1",
        "rxjs": "^6.4.0",
        "zone.js": "^0.9.0"
    }
}


Below are details of each of the dependencies and a link to the documentation for each:

  • @angular/common
    Common angular directives including NgIf, NgClass, NgForOf and pipes including AsyncPipe, UpperCasePipe, LowerCasePipe. Also includes the Angular HttpClient in the @angular/common/http subfolder.
    Docs: https://angular.io/api/common
  • @angular/compiler
    Angular template compiler, used by @angular/platform-browser-dynamic to convert templates to JavaScript code that can run in the browser.
  • @angular/core
    As the name suggests, these are the core services, utilities and functionality required by all Angular applications.
    Docs: https://angular.io/api/core
  • @angular/forms
    Includes providers and directives for building both template-driven and reactive forms.
    Docs: https://angular.io/api/forms
  • @angular/platform-browser
    Includes core functionality for running Angular applications in different supported browsers.
    Docs: https://angular.io/api/platform-browser
  • @angular/platform-browser-dynamic
    Includes providers and methods to compile, bootstrap and run Angular apps dynamically in the browser using JIT compilation.
    Docs: https://angular.io/api/platform-browser-dynamic
  • @angular/router
    Implements routing features which enable navigation between different routes (url paths) in an Angular application and mapping routes to different components.
    Docs: https://angular.io/guide/router
  • core-js
    A collection of polyfills that add support for features required by Angular that aren’t natively supported yet in several browsers.
    Docs: https://github.com/zloirock/core-js
  • rxjs
    Reactive Extensions Library for JavaScript, including an implementation of Observables which are returned by many Angular APIs and used throughout the Angular framework for handling asynchronous events.
    Docs: https://angular.io/guide/rx-library
  • zone.js
    Implements Zones for JavaScript, used by Angular for running change detection processes when native js operations raise events.
    Docs: https://github.com/angular/zone.js/


Install Angular 7 Development Dependencies

Run the following command from the project folder to install and save the npm packages required to develop, compile and bundle Angular 7 applications:

npm install --save-dev @types/node@11 angular2-template-loader@0 html-webpack-plugin@3 raw-loader@1 ts-loader@5 typescript@3 webpack@4 webpack-cli@3 webpack-dev-server@3

The command will download the packages into a node_modules folder and add them to the devDependencies property in the package.json file. So next time to install all of the packages you just need to run npm install and it will use the list in package.json.

The package.json should look like this after installing Angular 7 development dependencies with the above command:

{
    "name": "angular-7-tutorial",
    "version": "1.0.0",
    "dependencies": {
        "@angular/common": "^7.2.13",
        "@angular/compiler": "^7.2.13",
        "@angular/core": "^7.2.13",
        "@angular/forms": "^7.2.13",
        "@angular/platform-browser": "^7.2.13",
        "@angular/platform-browser-dynamic": "^7.2.13",
        "@angular/router": "^7.2.13",
        "core-js": "^3.0.1",
        "rxjs": "^6.4.0",
        "zone.js": "^0.9.0"
    },
    "devDependencies": {
        "@types/node": "^11.13.5",
        "angular2-template-loader": "^0.6.2",
        "html-webpack-plugin": "^3.2.0",
        "raw-loader": "^1.0.0",
        "ts-loader": "^5.3.3",
        "typescript": "^3.4.4",
        "webpack": "^4.30.0",
        "webpack-cli": "^3.3.0",
        "webpack-dev-server": "^3.3.1"
    }
}


Below are details of each of the dev dependencies and a link to the documentation for each:


Create tsconfig.json

Inside the project folder create a file named tsconfig.json. This file specifies the compiler options used by the TypeScript compiler to convert TypeScript files into JavaScript that will be understood by browsers.

Open tsconfig.json in VS Code, set target to "es5", emitDecoratorMetadata to true and experimentalDecorators to true. There are many more compiler options available, for a full list see https://www.typescriptlang.org/docs/handbook/compiler-options.html.

The tsconfig.json file should look like this:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "ES5"
    }
}


Below are details of each of the compiler options used:

  • emitDecoratorMetadata
    This options tells the TypeScript compiler to save type information from Angular components as metadata in the output JavaScript. The type information is used by Angular to support dependency injection.
    For a more detailed explanation: http://nicholasjohnson.com/blog/how-angular2-di-works-with-typescript/.
  • experimentalDecorators
    Enables the experimental Decorator feature of TypeScript. A Decorator is a special kind of declaration that can be attached to a class, method, accessor, property, or parameter, and are written as @Decorator. Angular uses decorators to declare what a class is (e.g. @Component, @NgModule, @Directive) and provide configuration metadata about the class.
    List of all decorators in Angular core package: https://angular.io/api/core#decorators.
  • target
    Specifies the JavaScript/ECMAScript target version that the TypeScript will be compiled to. "ES5" is currently the latest version which is supported by all modern browsers.
    More info about browser support for JavaScript versions: https://www.w3schools.com/js/js_versions.asp.


Create webpack.config.js

Inside the project folder create a file named webpack.config.js. This file specifies the configuration options used by webpack to compile and bundle an Angular app.

Webpack is a JavaScript module bundler that can be extended with loaders to handle other file types (e.g. TypeScript, HTML, CSS) and plugins to perform other tasks such as injecting generated JS bundles into an HTML template (html-webpack-plugin). More info available at the official webpack docs website: https://webpack.js.org/concepts.

Open webpack.config.js in VS Code and copy the following config:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/main.ts',
    resolve: {
        extensions: ['.ts', '.js']
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: ['ts-loader', 'angular2-template-loader']
            },
            {
                test: /\.(html|css)$/,
                use: 'raw-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({ template: './src/index.html' })
    ]
}


Below are details of each of the webpack config options used:

  • entry
    Specifies the entry point/s for webpack to begin. Webpack will find all of the direct and indirect dependencies of the entrypoint file to include in the output JavaScript bundle/s for the Angular application. If not set the default value is ./src/index.js, for this Angular app it is set to ./src/main.ts.
    Docs: https://webpack.js.org/concepts/entry-points/.
  • resolve.extensions
    Sets the list of extensions that webpack will use when attempting to resolve the location of module dependencies. Used to find the files for imported Angular modules and components.
    Docs: https://webpack.js.org/configuration/resolve/#resolveextensions.
  • module.rules
    Module rules are configured to tell webpack to transform specified files using loaders before adding them to the output bundle. The test property sets which file/s to transform and the use property sets which loader/s will do the transforming.
    The first above rule tells webpack to transform TypeScript (*.ts) files with the ts-loader and angular2-template-loader. The second rule tells webpack to transform HTML (*.html) & CSS (*.css) files with the raw-loader.
    Docs: https://webpack.js.org/concepts#loaders
  • plugins
    Plugins are used to extend the functionality of webpack to perform a wide range of tasks. The HtmlWebpackPlugin above injects the JavaScript bundle output from webpack into the specified html template (./src/index.html) to be run in the browser. Docs: https://webpack.js.org/concepts#plugins


Create src folder

Create a src folder in the project folder, this folder will contain all of the source code for the Angular 7 application.


Create app folder

Create an app folder in the src folder, this folder will contain all of the code for the Angular 7 AppModule that you will create shortly.

Angular applications are organised into modules, or in other words, Angular modules are the building blocks of Angular applications. An Angular module is used to group together related Angular components, services, directives etc. The tutorial application will contain a single Angular module (AppModule), as applications grow they can be split into multiple modules for maintainability. For more info on Angular Modules see https://angular.io/guide/architecture-modules


Create Angular App Component template

Create a file named app.component.html in the /src/app folder and copy the below HTML code into it.

The App Component template contains the HTML for the App Component that you will create in the next step. For now it will just contain a simple hello message that will display when we test our Angular 7 app. For more info on Angular templates see https://angular.io/guide/architecture-components#templates-and-views

It should look like this:

<h1>Hello Angular 7!</h1>


Create Angular App Component

Create a file named app.component.ts in the /src/app folder and copy the below TypeScript code into it.

An Angular component is a class that contains the logic to control a piece of the UI. A class becomes an Angular component when it is decorated with the @Component decorator. For more info on Angular components see https://angular.io/guide/architecture-components

The App Component contains the logic required to interact with and support the App Component template, at the moment the App Component template doesn't require any logic so the class is empty.

The @Component decorator contains two parameters, the selector: 'app' parameter tells Angular to inject an instance of this component wherever it finds the <app></app> HTML tag. The templateUrl: 'app.component.html' parameter tells Angular where to find the HTML template for this component.

It should look like this:

import { Component } from '@angular/core';

@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent {}


Create Angular App Module

Create a file named app.module.ts in the /src/app folder and copy the below TypeScript code into it.

An Angular module is a class used to group together related Angular components, services, directives etc. A class becomes an Angular module when it is decorated with the @NgModule decorator. For more info on Angular Modules see https://angular.io/guide/architecture-modules.

It should look like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }


Below are details of each of the @NgModule parameters used:

  • The imports: [BrowserModule] parameter tells Angular to import the BrowserModule into this module, which makes the components, directives and pipes in BrowserModule available to all components in the AppModule. The BrowserModule includes core functionality for running Angular applications in different supported browsers.
  • The declarations: [AppComponent] parameter declares that the AppComponent belongs to this module and makes it available to all other components and templates within this module.
  • The bootstrap: [AppComponent] parameter tells Angular to bootstrap the AppComponent when the AppModule is bootstrapped. For more info on Angular bootstrapping see https://angular.io/guide/bootstrapping.


Create Angular 7 Polyfills File

Create a file named polyfills.ts in the /src folder and copy the below TypeScript code into it.

Some features used by Angular 7 are not yet supported natively by all major browsers, polyfills are used to add support for features where necessary so your Angular 7 application works across all major browsers.

import 'core-js/features/reflect';
import 'zone.js/dist/zone';


Create Angular 7 Main (Bootstrap/Launch) File

Create a file named main.ts in the /src folder and copy the below TypeScript code into it.

The main file is the entry point used by Angular to bootstrap/launch the application's root module (AppModule) in the browser.

It calls bootstrapModule(AppModule); on platformBrowserDynamic() to compile and bootstrap AppModule in the browser with JIT compilation. For more info on Angular bootstrapping see https://angular.io/guide/bootstrapping.

import './polyfills';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);


Create Angular 7 Main Index Html File

Create a file named index.html in the /src folder and copy the below HTML code into it.

The main index.html file is the initial page loaded by the browser that kicks everything off. Webpack bundles all of the javascript files together and injects them into the body of the index.html page so the scripts get loaded and executed by the browser.

Angular injects the AppComponent into the <app>Loading...</app> tag because it matches the selector defined in the component metadata. The Loading... message is the default text displayed until Angular has finished booting up.

<!DOCTYPE html>
<html>
<head>
    <base href="/" />
    <title>Angular 7 Tutorial</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- bootstrap css -->
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <app>Loading...</app>
</body>
</html>


Add start script to package.json

Open package.json in VS Code and the following start script below the version property:

"scripts": {
  "start": "webpack-dev-server --mode development --open"
}


The start script is run with the command npm start. This script will start the webpack-dev-server in development mode and automatically open the browser with the --open argument.

The updated package.json should now look like this:

{
    "name": "angular-7-tutorial",
    "version": "1.0.0",
    "scripts": {
        "start": "webpack-dev-server --mode development --open"
    },
    "dependencies": {
        "@angular/common": "^7.2.13",
        "@angular/compiler": "^7.2.13",
        "@angular/core": "^7.2.13",
        "@angular/forms": "^7.2.13",
        "@angular/platform-browser": "^7.2.13",
        "@angular/platform-browser-dynamic": "^7.2.13",
        "@angular/router": "^7.2.13",
        "core-js": "^3.0.1",
        "rxjs": "^6.4.0",
        "zone.js": "^0.9.0"
    },
    "devDependencies": {
        "@types/node": "^11.13.5",
        "angular2-template-loader": "^0.6.2",
        "html-webpack-plugin": "^3.2.0",
        "raw-loader": "^1.0.0",
        "ts-loader": "^5.3.3",
        "typescript": "^3.4.4",
        "webpack": "^4.30.0",
        "webpack-cli": "^3.3.0",
        "webpack-dev-server": "^3.3.1"
    }
}


Start Angular 7 Application!

Run the command npm start from the project root folder (where the package.json is located) to launch the Angular 7 application.

 


Need Some Angular 7 Help?

Search fiverr for freelance Angular 7 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by