Getting started with TsLint and tslint-consistent-codestyle in Angular 5+ projects, Part 1: Visual Studio Code

 

Introduction

This article will show you how to integrate TsLint and the consistent codestyle extension to your Angular solution in order to ensure consistent coding standards across your code base.

In this tutorial, Angular 5 and Visual Studio Code will be used.

Step 1

After setting  your angular app, download TsLint for Visual studio code : https://marketplace.visualstudio.com/items?itemName=eg2.tslint

Step 2

Install the tslint-consistent-codestyle npm package. This package adds many useful coding rules not available with the native TsLint, such as naming-convention which allows you to control the way a variable, a function or really anything will be declared.

npm install --save-dev tslint-consistent-codestyle

Step 3

Replace the content of tslint.json by this content (you can edit these rules, they are only just a suggestion):

{
  "rulesDirectory": [
    "node_modules/codelyzer",
    "tslint-consistent-codestyle"
  ],
  "rules": {
    "arrow-return-shorthand": true,
    "callable-types": true,
    "class-name": true,
    "comment-format": [
      true,
      "check-space"
    ],
    "curly": true,
    "deprecation": {
      "severity": "warn"
    },
    "eofline": true,
    "forin": true,
    "import-blacklist": [
      true,
      "rxjs",
      "rxjs/Rx"
    ],
    "import-spacing": true,
    "indent": [
      true,
      "spaces"
    ],
    "interface-over-type-literal": true,
    "label-position": true,
    "max-line-length": [
      true,
      140
    ],
    "member-access": true,
    "member-ordering": [
      true,
      {
        "order": [
          "static-field",
          "instance-field",
          "static-method",
          "instance-method"
        ]
      }
    ],
    "no-arg": true,
    "no-bitwise": true,
    "no-console": [
      true,
      "debug",
      "info",
      "time",
      "timeEnd",
      "trace"
    ],
    "no-construct": true,
    "no-debugger": true,
    "no-duplicate-super": true,
    "no-empty": false,
    "no-empty-interface": true,
    "no-eval": true,
    "no-inferrable-types": [
      true,
      "ignore-params"
    ],
    "no-misused-new": true,
    "no-non-null-assertion": true,
    "no-shadowed-variable": true,
    "no-string-literal": false,
    "no-string-throw": true,
    "no-switch-case-fall-through": true,
    "no-trailing-whitespace": true,
    "no-unnecessary-initializer": true,
    "no-unused-expression": true,
    "no-use-before-declare": true,
    "no-var-keyword": true,
    "object-literal-sort-keys": false,
    "one-line": [
      true,
      "check-open-brace",
      "check-catch",
      "check-else",
      "check-whitespace"
    ],
    "prefer-const": true,
    "quotemark": [
      true,
      "single"
    ],
    "radix": true,
    "semicolon": [
      true,
      "always"
    ],
    "triple-equals": [
      true,
      "allow-null-check"
    ],
    "typedef-whitespace": [
      true,
      {
        "call-signature": "nospace",
        "index-signature": "nospace",
        "parameter": "nospace",
        "property-declaration": "nospace",
        "variable-declaration": "nospace"
      }
    ],
    "unified-signatures": true,
    "variable-name": false,
    "whitespace": [
      true,
      "check-branch",
      "check-decl",
      "check-operator",
      "check-separator",
      "check-type"
    ],
    "directive-selector": [
      true,
      "attribute",
      "app",
      "camelCase"
    ],
    "component-selector": [
      true,
      "element",
      "app",
      "kebab-case"
    ],
    "no-output-on-prefix": true,
    "use-input-property-decorator": true,
    "use-output-property-decorator": true,
    "use-host-property-decorator": true,
    "no-input-rename": true,
    "no-output-rename": true,
    "use-life-cycle-interface": true,
    "use-pipe-transform-interface": true,
    "component-class-suffix": true,
    "directive-class-suffix": true,
    "ordered-imports": [
      true,
      {
        "import-sources-order": "any",
        "named-imports-order": "case-insensitive"
      }
    ],
    "naming-convention": [
      true,
      {"type": "default", "format": "camelCase", "leadingUnderscore": "forbid", "trailingUnderscore": "forbid"},
      {"type": "method", "modifiers": "public", "format": "camelCase"},
      {"type": "member", "modifiers": "private", "leadingUnderscore": "require"},
      {"type": "type", "format": "PascalCase"}
    ],
    "typedef": [
      true,
      "call-signature",
      "property-declaration"
    ]
  }
}

Step 4

Run the command:

npm run lint

And check for errors in the terminal (some errors might not appear with Tslint extension)

Example:

Step 5

Fix the errors or edit your rules 🙂

Getting started with TsLint and tslint-consistent-codestyle in Angular 5+ projects, Part 2: VSTS builds integration

 

Introduction

This article will help you configure TSLINT and some more code style rules to enforce consistent code style in your Angular application.
We are using Angular 5 in Visual Studio Code for this tutorial and VSTS to run a Continuous Integration (CI) build.

Step 1

Create a build definition in VSTS.

Configure your source repository location.

Step 2

Setup your agent phase, name it and select an Agent queue:

Step 3

Install dependencies simply by selecting the “install” command:

Step 4

Configure the build using a “custom” command like this:

Step 5

Configure TsLint using a “custom” command like this:

Step 6

Run the VSTS CI build and check your log 😊

If your code doesn’t respect your TsLint rules it should make your build fail:

 

Good luck 😉

Getting started with translation in Angular 5 with ngx-translate

Introduction

Ngx-translate is an internationalization (i18n) library for Angular.

Let’s see how it works in an Angular 5 project with Visual Studio code

Step 1

Download following packages:

Core package

npm install @ngx-translate/core@^9.1.1 -–save

It’s important not to use version 10 because it’s only compatible with Angular 6

If you still use the Angular 4 get the latest compatible version (7.2.2).

Http loader package

npm install @ngx-translate/http-loader --save

if you’re still on Angular <4.3, please use Http from @angular/http with http-loader@0.1.0

Step 2

Create a httpLoaderFactory that inherits from TranslateHttpLoader

import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function httpLoaderFactory(httpClient: HttpClient): TranslateHttpLoader {
   return new TranslateHttpLoader(httpClient, './assets/i18n/', '.json');
}

Assets/i18n will contains json resource file for each language: [lang].json

Step 3

Create languages files:

Example:

{
   "APP" : {
              "TITLE" : "ngx-translate demonstration",
              "BODY" : "It works very well!"
           }
}

Step 4

Setup app.module.ts by importing required modules:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { httpLoaderFactory } from './services/httpLoaderFactory';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      HttpClientModule,
      TranslateModule.forRoot({
         loader: {
            provide: TranslateLoader,
            useFactory: httpLoaderFactory,
            deps: [HttpClient]
         }
      }),
   ],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

Step 5

Set language to use like this in your component:

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
   selector:'app-root',
   templateUrl:'./app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {
   title='app';

   constructor(private_translate:TranslateService) {
      this._translate.setDefaultLang('en');
      this._translate.use('en');
   }
}

SetDefaultLang is used to set a fallback language when a translation isn’t found in the current language. use the lang to use, if the lang isn’t available, it will use the current loader to get them.

Build then a method that can allow to switch to another language.

Step 6

Test your app!

Example:

<div style="text-align:center">
   <h1>
      {{'APP.TITLE' | translate}}
   </h1>
</div>

Result:

Easy right ? 😉