Skip to main content

6 posts tagged with "angularcli"

View All Tags

· 5 min read

It's been almost a week since Angular 9 was released which included several new features such as new Ivy Renderer, SSR, Type checking etc. In this post, i will be going through on how to build and deploy an Angular9 application as a static website to Azure with GitHub Actions.

Prerequisites:

  • Github Account
  • Azure Account
  • VSCode

Step 1: Install latest Angular CLI

In order to create the Angular application , you need to install the latest angular cli, which could be done with the following command,

 npm install -g @angular/cli@latest

Step 2: Create new Angular9 App

Run the following command to create the Angular9 app with the default template. Let's name the application as ga-azure

ng new ga-azure

Step 3: Install the Hexa.run CLI

We will use the package by Wassim Chegham to deploy the application to Azure. Next step in your Angular project make sure to install the Hexa.run CLI as a prod dependency as you can see from the package.json of this project.

npm i -g @manekinekko/hexa

Step 4: Login to Azure account

Next step is to create the necessary resources to deploy the angular application. In this way, we will deploy our application to static website for Azure Storage which is the optimum option to host a single page application (SPA) on Azure.Hosting a SPA in pure Storage is by far the cheapest and most efficient way of running in Azure.

You can login to azure account with the command,

npm run hexa:login

which will list down the available subscriptions and you need to pick the subscription where you want to deploy the application.

Step 5: Initiate the Hexa Settings

Next step is to initiate the configuration needed for the deployment of the application. Run the Hexa CLI command as follows,

npm run hexa:init

which will ask for few inputs from the user such as the project name, storage account name and the destination folder. Eventually, you will see a new file generated as hexa.json which will look like the below,

{
"subscription": {
"name": "Azure Demo"
},
"project": {
"location": "westeurope",
"name": "ga-azure"
},
"storage": {
"location": "westeurope",
"name": "gaazure10940"
},
"hosting": {
"folder": "./gist/ga-azure"
}
}

Now you are good with all the necessary things needed to deploy the application with github action.

Step 6: Generate Service Principal

You need to use the service principal identity mechanism to do the authorization of the deployment. In order to generate the service principal using hexa, run the below command,

npm run hexa:ci

Hexa.run will automatically:

  1. create an Azure resource group (or lets you choose an existing one)
  2. create the Azure storage account
  3. configure the storage account and make it static-website ready
  4. upload the angular bundle.
  5. prints the generated URL from the Azure service.

Also it will generate the necessary credentials as a JSON and make a note of them.

{
appId: 'xx4362xx-aaxx-40xx-8bxx-xx6ea0c351xx',
displayName: 'ga-azure',
name: 'http://ga-azure',
password: 'xxce72xx-1axx-44xx-81xx-35xxb15xxa1e',
tenant: 'xxf988xx-86xx-41xx-91xx-2d7cd011dbxx'
}

Step 7 : Commit and push to the Github Repository

Once you are done with all the above steps , you can commit your changes and push to the remote repository on Github.

git remote add origin https://github.com/sajeetharan/ga-azure.git
git add -A && git commit -m "First commit"
git push origin master

Step 8 : Create Github Actions Workflow

Now it's the time to create the Actions workflow, you can create a new workflow by navigating to actions and click New Worfklow. There are few sample template workflows available , in this case we will use own workflow. So you need to click on setup workflow yourself.

Setting up own workflow GitHub Actions

Immediately you could see new workflow.yml file created where you need to add the steps and actions needed to deploy the app. Here is the workflow file look like after adding all the steps.

name: Deploy to Azure with Hexa.ru
on:
push:
branches:
- master
- release/*

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [12.x]

steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: npm install
run: |
npm install
- name: npm build, and deploy
env:
AZURE_SERVICE_PRINCIPAL_ID: ${{ secrets.AZURE_SERVICE_PRINCIPAL_ID }}
AZURE_SERVICE_PRINCIPAL_PASSWORD: ${{ secrets.AZURE_SERVICE_PRINCIPAL_PASSWORD }}
AZURE_SERVICE_PRINCIPAL_TENANT: ${{ secrets.AZURE_SERVICE_PRINCIPAL_TENANT }}
run: |
npm run hexa:login
npm run build -- --prod
npm run hexa:deploy

As you could see, the steps are very much simple starting with installing the dependencies and deploying the angular application using the hexa:deploy command.

Also you need to configure the secrets in the github repository which were generated in the step 6. You can create a new secret by navigating to settings and then secrets. you need to define the below secrets which are associated with the service principal.

Github Secrets

The rest in the workflow can be easily understood as its about the environment and the trigger(whenever someone push the changes to master/release there should be a build)

Step 9 : See Github Actions in Action

Immediately when you save the workflow.yml you can see there will be a new build triggered and the steps are executed, which you can notice in the Actions tab as follows,

Deploy using hexa:run

You will be able to access the application in the url generated once the application is deployed which will look like https://gaazure10940.z6.web.core.windows.net/

That's all you need to do inorder to deploy the Angular application to Azure. If you need to include end to end testing and different tasks you could simply modify the flow and it. Github Actions definitely a future to believe in! Try this out and let me know if you have any queries! Cheers!

· 5 min read

It's been almost a week since Angular 9 was released which included several new features such as new Ivy Renderer, SSR, Type checking etc. In this post, i will be going through on how to build and deploy an Angular9 application as a static website to Azure with GitHub Actions.

Prerequisites:

  • Github Account
  • Azure Account
  • VSCode

Step 1: Install latest Angular CLI

In order to create the Angular application , you need to install the latest angular cli, which could be done with the following command,

 npm install -g @angular/cli@latest

Step 2: Create new Angular9 App

Run the following command to create the Angular9 app with the default template. Let's name the application as ga-azure

ng new ga-azure

Step 3: Install the Hexa.run CLI

We will use the package by Wassim Chegham to deploy the application to Azure. Next step in your Angular project make sure to install the Hexa.run CLI as a prod dependency as you can see from the package.json of this project.

npm i -g @manekinekko/hexa

Step 4: Login to Azure account

Next step is to create the necessary resources to deploy the angular application. In this way, we will deploy our application to static website for Azure Storage which is the optimum option to host a single page application (SPA) on Azure.Hosting a SPA in pure Storage is by far the cheapest and most efficient way of running in Azure.

You can login to azure account with the command,

npm run hexa:login

which will list down the available subscriptions and you need to pick the subscription where you want to deploy the application.

Step 5: Initiate the Hexa Settings

Next step is to initiate the configuration needed for the deployment of the application. Run the Hexa CLI command as follows,

npm run hexa:init

which will ask for few inputs from the user such as the project name, storage account name and the destination folder. Eventually, you will see a new file generated as hexa.json which will look like the below,

{
"subscription": {
"name": "Azure Demo"
},
"project": {
"location": "westeurope",
"name": "ga-azure"
},
"storage": {
"location": "westeurope",
"name": "gaazure10940"
},
"hosting": {
"folder": "./gist/ga-azure"
}
}

Now you are good with all the necessary things needed to deploy the application with github action.

Step 6: Generate Service Principal

You need to use the service principal identity mechanism to do the authorization of the deployment. In order to generate the service principal using hexa, run the below command,

npm run hexa:ci

Hexa.run will automatically:

  1. create an Azure resource group (or lets you choose an existing one)
  2. create the Azure storage account
  3. configure the storage account and make it static-website ready
  4. upload the angular bundle.
  5. prints the generated URL from the Azure service.

Also it will generate the necessary credentials as a JSON and make a note of them.

{
appId: 'xx4362xx-aaxx-40xx-8bxx-xx6ea0c351xx',
displayName: 'ga-azure',
name: 'http://ga-azure',
password: 'xxce72xx-1axx-44xx-81xx-35xxb15xxa1e',
tenant: 'xxf988xx-86xx-41xx-91xx-2d7cd011dbxx'
}

Step 7 : Commit and push to the Github Repository

Once you are done with all the above steps , you can commit your changes and push to the remote repository on Github.

git remote add origin https://github.com/sajeetharan/ga-azure.git
git add -A && git commit -m "First commit"
git push origin master

Step 8 : Create Github Actions Workflow

Now it's the time to create the Actions workflow, you can create a new workflow by navigating to actions and click New Worfklow. There are few sample template workflows available , in this case we will use own workflow. So you need to click on setup workflow yourself.

Setting up own workflow GitHub Actions

Immediately you could see new workflow.yml file created where you need to add the steps and actions needed to deploy the app. Here is the workflow file look like after adding all the steps.

name: Deploy to Azure with Hexa.ru
on:
push:
branches:
- master
- release/*

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [12.x]

steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: npm install
run: |
npm install
- name: npm build, and deploy
env:
AZURE_SERVICE_PRINCIPAL_ID: ${{ secrets.AZURE_SERVICE_PRINCIPAL_ID }}
AZURE_SERVICE_PRINCIPAL_PASSWORD: ${{ secrets.AZURE_SERVICE_PRINCIPAL_PASSWORD }}
AZURE_SERVICE_PRINCIPAL_TENANT: ${{ secrets.AZURE_SERVICE_PRINCIPAL_TENANT }}
run: |
npm run hexa:login
npm run build -- --prod
npm run hexa:deploy

As you could see, the steps are very much simple starting with installing the dependencies and deploying the angular application using the hexa:deploy command.

Also you need to configure the secrets in the github repository which were generated in the step 6. You can create a new secret by navigating to settings and then secrets. you need to define the below secrets which are associated with the service principal.

Github Secrets

The rest in the workflow can be easily understood as its about the environment and the trigger(whenever someone push the changes to master/release there should be a build)

Step 9 : See Github Actions in Action

Immediately when you save the workflow.yml you can see there will be a new build triggered and the steps are executed, which you can notice in the Actions tab as follows,

Deploy using hexa:run

You will be able to access the application in the url generated once the application is deployed which will look like https://gaazure10940.z6.web.core.windows.net/

That's all you need to do inorder to deploy the Angular application to Azure. If you need to include end to end testing and different tasks you could simply modify the flow and it. Github Actions definitely a future to believe in! Try this out and let me know if you have any queries! Cheers!

· 9 min read

The wait is over and Angular 7 is out, finally time has come to write about some tips to build fast angular application. In this blog i will share my experience with practices that you need to follow when you are starting a new project.

There are three primary things important when you are starting to build an application with Angular.

  1. Project Architecture
  2. Application Infrastructure
  3. Conventions,Formating and Tooling

CONVENTIONS,FORMATTING AND TOOLING

  • Always place the Angular application outside your backend code

Keep the application in its own repository so that can be deployed/version separately. It will also help in tooling. One key rule is to treat it as a real application.

  • Use VS Code for best experience

Encourage your team to switch to VS Code which has immense support for development with Angular. It has strong support for extensions used in Angular projects and well-regarded by front end community.

  • Use Tooling

It will kill all the disagreements. Use VSCode extensions such as TSLint, Angular Language ervice, Prettier, EditorConfig and SCSS intellisence.

  • Naming and Syntax Conventions

Always use Singular for Modules and Singular or Plural for  components/ services/ directives and pipes

  • Use Angular style commit messages

Examples :

'feat(notification.service): add display param'

'refactor(order models): rename couponId to couponCodeId

  • Use Codelyzer to do statistical analysis on Angular/Typescript code

It's a set of tslint rules for static code analysis of Angular TypeScript projects. If you are doing continuous deployment configure with your pipeline.

  • Follow consistent structure

If you are using Angular-Cli always follow the same pattern to generate the necessary files so that it will be consistent throughout the application.

  • Absolute path for ES Modules

Always use absolute path that would help in refactoring(moving files around or renaming) and very easy to organize files.

  • Do not use null and assign default values

In the templates always use safe navigation type operator which can help in preventing the following annoying errors "cannot read property "name" of undefined"

  • Choose Intelligent defaults and be consistent

'' for string - declare string with default value ""

0 for number - declare number with default value 0**[]** for arrays - declare array with default value []

  • Build small reusable components

Don't make your component code go more than 300 lines. Split the pieces that can be reused in a component and make them as a new component. The component should be made as dumb as possible. It should not dependent on any inputs or outputs provided, it should work simple. General rule of thumb is to make the last child in the component tree to be the dumbest. Reusable components reduce the duplication of code and you can make changes easily.

Components should deal only with the presentation logic Don't have logic other than the presentation logic. Components are designed for presentational purposes and only should focus on what the view should do. Business logics should be separated out to services/methods from the presentation/view logic.

  • Use trackBy in ngFor Loops

DOM manipulations are always expensive, immutable practices always generate a new collection which will result in bad performance. When your array changes, Angular will be rendering the whole DOM tree, when you use trackBy, it will know which elements has changed and will make changes only to those particular elements.

  • const vs let

Make use of let and const wherever its appropriate. It will help a lot in identifying issues when a value is reassigned to a constant accidentally with a compile error and it improves the readability of the code.

  • Pipable Operators

With Angular version above 5.5 , you can use pipeable operators which are tree-shakable (only the code need to execute will be included when they are imported) and it will be easy to identify unused code in the component files.

  • Subscribe in template

Rather than subscribe in service or async popes unsubscribe themself automatically it will make the code simpler by stopping the need to manually manage subscriptions which could cause a memory leak. When using subscribe, the risks can be eliminated by using a lint rule to detect unsubscribed observables.

  • Clean up subscriptions

When you subscribe in the component to observables, make sure you unsubscribe from them completely with operators like take,takeUntil,Unsubscribe etc

  • Use appropriate Operators

switchMap: when you want to ignore the previous emissions when there is a new emission mergeMap: when you want to concurrently handle all the emissions

concatMap: when you want to handle the emissions one after the other as they are emitted

exhaustMap: when you want to cancel all the new emissions while processing a previous emisssion

  • Stop using any:type everything in the code

Always declare variables or constants with a type other than any. This is the advantage that you have with Typescript when you have good typings in your application which makes refactoring easier and safe and also avoid unintented issues.

  • Use lint rules as you need

TSLINT has various options built-in already like no-any, no-magic-numbers, no-console, etc that you can configure in your tslint.json to enforce certain rules in your code base

  • Dont Repeat Yourself

One of the common mistake that i did as a developer was copy paste the same code in all components. Do not repeat or have the same code in different places in the code base. Extract the repeating code and make them as a generic method which could be used in different components.

  • Avoid Logic in component templates

Place the logic in the component file rather than on the template such as && condition since it cannot be possible to unit test also it is prone to more bugs when changing template code

APPLICATION INFRASTRUCTURE

  • Lazy load everything

When you are building application with large number of modules always do lazy loading which could improve your application performance by large margin. Angular CLI makes this easy and helps break up your app into logical bundles. With Lazy loading users only pay for what they want. For example, Sensitive (admin only) code will not be downloaded for users that don't have access.

  • Analyze your bundle

If you are using any bundling mechanism always analyze the size of the bundle generated. You can use webpack-bundle-analyzer for example and you can improve the performance there on.

Install source map explorer

  • npm install -g source-map-explorer

Build with source map

  • ng build --prod -sm

Inspect your bundle

  • source-map-explorer dist/vendor*.js
  • Use Debug.Service.ts to track errors

It is always good to have a common debug service to assist with the development. This service could replace the calls to console.log.  You can use Visual studio extension codelensto track down the calls with console.log.This service can be toggled at run time with local storage value and needs to be switched off with production builds.

  • RXJS Operators

When using it becomes handy to handle so many operations with Rxjs operators. Always remember to include/import only the things you need. Also make sure to add noUnusedLocals in the tsconfig.

  • Use ES Modules for helper functions

With ES Modules it is really easy to import only available when thy are needed.

  • Keep environment values in environment files

It becomes really easy and very helpful to manage environment values when it comes to continuous improvement and continuous deployment.

  • Avoid Base classes / Inheritance

Even though Angular is build with Typescript, many of the developers tend to use services from a base class. This should be only if necessary. It will result in restricting the flexibility as when your app grows and use cases changes.

Also create a utility.services.ts to contain all the base helper services. For ex: debug.service.ts , notification.service.ts  session.service.ts can be placed within utility.service.ts which helps in preventing app wide changes to base constructor.

  • Use Obseravable/State Management Patterns

It is really important to follow Redux patern (RxJS) to have a better state management in application. Also in components use ngUnsubscribefor complex Observable management in Components. Use shareReplayoperator and/or async pipe for simpler cases

  • More things to consider on Application

Always consider browser caching and application versioning. Test the update process and the experience across browsers. Always figure out user experience and continuously work on it. Use global error handler to store report errors to API and do not access Document or Window Objects manually.

PROJECT ARCHITECTURE

  • One of the primary thing that you need to consider before starting a project is the architecture on how to build flexible,simple,fast application. It needs lot of planning and consistency to get the basement correct. Building things is really hard enough. When it comes to building Angular application i would recommend to follow the following Guidelines
  • One best place to start with good practices is by following the recommended style guide. You need to take what works for your team and skip what does not work. Also try to learn from others mistakes or any other projects that you've already worked with.
  • While designing module,s it is really important to know about how to structure your modules and what should go under Feature/Core/Shared Modules.

  • Keep a flat file structure as long as possible which means you should not add hierarchy with less than 20 files and you can always move files as the app grows larger.
  • Maintain your application version using the package.json which could be embedded in your app.
  • Use package management tooling to guarantee reproducible dev environment and builds.
  • Set custom host for the application by changing the default url.
  • Use proxies if you are integrating with an API.
  • Lets look at what you can do while implementing the above architecture in your application

Follow this repository in order to get started

The above are the some of the most important practices that you need to follow when you are starting a  new project with Angular. Hope this helps someone out there.

· 4 min read

This should help all the Angular developers out there to test yourself on the knowledge on Angular. I have listed down the concepts/questions from various sources such as Stackoverflow,Medium etc. Will be continuing this with 2 more posts.

1. What's new in Angular 6

  • Angular Elements - Angular Elements is a project that lets you wrap your Angular components as Web Components and embed them in a non-Angular application.
  • New Rendering Engine: Ivy - increases in speed and decreases in application size.
  • Tree-shakeable providers - a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute
  • RxJS 6 - Angular 6 now uses RxJS 6 internally, and requires you to update your application also. RxJS released a library called rxjs-compat, that allows you to bump RxJS to version 6.0 even if you, or one of the libraries you’re using, is still using one of the “old” syntaxes.
  • ElementRef - in Angular 5.0 or older, is that the said ElementRef had its nativeElement property typed as any. In Angular 6.0, you can now type ElementRef more strictly.
  • Animations - The polyfill web-animations-js is not necessary anymore for animations in Angular 6.0, except if you are using the AnimationBuilder.
  • i18n - possibility to have “runtime i18n”, without having to build the application once per locale

2. Difference between "Constructor" and "ngOnInit

  • The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses.

  • ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component. We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice).

3. Difference between "declarations", "providers" and "import" in NgModule

  • imports makes the exported declarations of other modules available in the current module. It is also used to import supporting modules likes FormsModule, RouterModule, CommonModule, or any other custom-made feature module.
  • declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
  • providers are to make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as dependency.

 

A special case for **providers**are lazy loaded modules that get their own child injector. **providers**of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

Example : 

https://gist.github.com/sajeetharan/c3e872abd22fe0b43e7b8ae47289d018

4.Ahead of Time Compilation

 Angular Ahead-of-Time compiler pre-compiles application components and their templates during the build process.Apps compiled with AOT launch faster for several reasons

  • Application components execute immediately, without client-side compilation.
  • Templates are embedded as code within their components so there is no client-side request for template files.
  • You don't download the Angular compiler, which is pretty big on its own.
  • The compiler discards unused Angular directives that a tree-shaking tool can then exclude.
  • Also has small bundle size and faster load time.

5. Need of lazy loading modules in Angular.

Lazy loading is useful when the application size is growing. In lazy loading, feature module will be loaded on demand and hence application start will be faster.To load a feature module lazily we need to load it using loadChildren property in route configuration and that feature module must not be imported in application module.

· 2 min read

Hey guys, There has not been a  proper resource to have a checklist to make sure that applicaiton is flawless.I decided to write a simple tips on checklist items needed before you deploy your app to production.Following are a few Angular Code Review Checklists useful while doing a peer review of Angular code. Make sure to check these when you are building a production ready application

#1 - Code modularity  

Layered Code with good Modularity.

#2 - Component per file 

Each file must not contain more than one Component/Controller, etc.

#3 - Routing

Always configure routing with lazy loading

#4 - Shared resources at centralized location

Store images/language translations under assets

#5 - 3rd Party libraries 

 If you are integrating with any 3rd party libraries make sure to check for Security Flaws

#6 - Data security 

Use  Encryption of Sensitive Data

#7 - Offline data security

Consider security if you are storing Data in localstorage or session storage.

#8 - Cookies data and handwiring of secrets 

 Security Flaws

#9 - Don't use pipe/functions in the template

Calling function binding in the template will lead to  performance issue

#10 - Change detection + state management & reactive extensions

Use RxJS, NgRx/Store (or Redux)

#11 - Use javascript or typescript

 Stick to ONE & Avoid Hybrid

#12 - Don't use pipe/functions in the template

 Bundling, Chunking, Treeshaking, Minification, Uglification, Compression

#13 - ECMAscript compatibility - ES7

#14 - Angular Style Guide (Official Reference)

 https://angular.io/guide/styleguide

#15 - Async service

 Adequate and Appropriate use of it.

#16 - Hierarchical components,models,interfaces etc

#17 - Constants

No-Scattered Hard-Coded constants data but must be at one place.

#18 - Images,fonts and other static files

Place them in respective directories and not scattered across.

#19 - TSLint.json

To follow Angular Style Guide in order to run SonarQube or Codelyzer. Follow https://github.com/Angular-Projects-V-1-to-X/codelyzer

#20 - Finally to improve performance 

Refer the steps  - https://github.com/mgechev/angular-performance-checklist

Hope it helps all the developers out there.