Friday, October 23, 2020

Guide for Angular Strict Mode

Leave a Comment


Angular announced a strict opt-in mode that allows us to perform more build time optimization and help you deliver faster applications. When you create a new project or workspace, you have an option to create in a strict mode using --strict option.


ng new projectname --strict

  • With the help of this command, create a new project or project with a new option that improves maintainability, allow the CLI to perform advanced optimization on your application.
  • --strict is an optional setting for creating an angular project application. If we create a project with --strict mode then it helps to improve maintainability, catch bugs ahead of time. 

Specifically, the strict flag does the following:

  • Enables strict mode in Typescript.
  • Turns template type checking too strict means turns on strict Angular compiler flags
  • strictTemplates and strictinjectionParameters.
  • Reduce default bundle budgets by as much as 75 %.
  • Configures tslint rules to prevent declarations of type any.
  • Configures your app to enable more advanced tree-shaking.

Tree-shaking:


Tree shaking means that code that is in your project but that code cannot be used or referenced anywhere and it will be dropped. Like if you import a full library and use only one function of this library then, it will reduce compile code size.

  • If you are creating a new project or workspace without using --strict mode, then the strict option should not be added in the tsconfig.json file.

This is the basic tsconfig.json file without using the --strict option.


{

  "compileOnSave"false,

  "compilerOptions": {

    "baseUrl""./",

    "outDir""./dist/out-tsc",

    "sourceMap"true,

    "declaration"false,

    "downlevelIteration"true,

    "experimentalDecorators"true,

    "module""esnext",

    "moduleResolution""node",

    "importHelpers"true,

    "target""es2015",

    "typeRoots": [

      "node_modules/@types"

    ],

    "lib": [

      "es2018",

      "dom"

    ]

  },

  "angularCompilerOptions": {

    "fullTemplateTypeCheck"true,

    "strictInjectionParameters"true

  }

}

 

  • If you are using --strict mode, there are some additional typescript compiler options, and an angular compiler option will be added in the tsconfig.json file.

{

  "compileOnSave"false,

  "compilerOptions": {

    "baseUrl""./",

"outDir""./dist/out-tsc",

    "forceConsistentCasingInFileNames"true,

    "strict"true,

    "noImplicitReturns"true,

    "noFallthroughCasesInSwitch"true,

    "sourceMap"true,

    "declaration"false,

    "downlevelIteration"true,

    "experimentalDecorators"true,

    "moduleResolution""node",

    "importHelpers"true,

    "target""es2015",

    "module""es2020",

    "lib": [

      "es2018",

      "dom"

    ]

  },

  "angularCompilerOptions": {

    "strictInjectionParameters"true,

    "strictInputAccessModifiers"true,

    "strictTemplates"true

  }

}

 


This is the Typescript compiler option:

  • "forceConsistentCasingInFileNames": true,

  • "strict": true,

  • "noImplicitReturns": true,

  • "noFallthroughCasesInSwitch": true,


This is the Angular compiler option:

  • "strictInjectionParameters": true,

  • "strictInputAccessModifiers": true,

  • "strictTemplates": true


If you like to have your Typescript type checking to be stricter in your project, there are a few settings that can be turned on in the tsconfig.json file.

  • strictNullChecks

  • stricPropertyInitialization

  • noImplicitAny

  • strictFunctionTypes

  • strictBindCallApply


strictNullChecks


strictNullChecks property protects from assigning undefined and null values in code. In the tsconfig.json file, we will enable this property by adding the strictNullChecks option.


"compilerOptions": {
"strictNullChecks": true,
} 


When strictNullChecks are false, then undefined and null are considered to be valid values of all types. When strictNullChecks are true, then undefined and null have their distinct type and if you try to use them it will give a type error.


strictPropertyInitialization


When strictPropertyInitialization is set to be true, then Typescript will raise an error when a class property was declared but not assigned within the constructor. In the tsconfig.json file, we will enable this property by adding the strictPropertyInitialization option.


"compilerOptions": {
"strictPropertyInitialization ": true,
}


Let’s see a simple example:

 

  namestring;

  emailstring;

 

  constructor (namestring) {

    this.name = name;

  }


In this example, the name is defined in the constructor but email is not defined in the constructor.


  • One way to solve the error is to give the email property a type that includes undefined. 

email: string | undefined;


Another way to solve the error is to add the email parameter in the constructor, which is assigned to the email property.


 

  namestring;

  emailstring;

  constructor(namestringemailstring) {

    this.name = name;

    this.email = email;

  }


noImplicitAny


The Default value is false unless it is set to true. In some cases when no type of annotations is available, then Typescript will be defined a type of any for a variable. In the tsconfig.json file, we will enable this property by adding the noImplicitAny option.


"compilerOptions": {
"noImplicitAny": true,
}


strictFunctionTypes:


The Default value is false unless it is set to true. When strictFunctionTypes are set to true, then functions parameters are checked more correctly. In the tsconfig.json file, we will enable this property by adding the strictFunctionTypes option.


"compilerOptions": {
"strictFunctionTypes ": true,
}


strictBindCallApply


Whenever strictBindCallApply set, Typescript will confirm to make sure that the inbuilt methods of functions bind, call and apply are invoked with the correct argument for the function. The Default value is false unless it is set to true. In the tsconfig.json file, we will enable this property by adding the strictBindCallApply option.


"compilerOptions": {
"strictBindCallApply": true,
}

  • Let’s see a simple example of strictBindCallApply:

function demofunction(xstring) {

    return x;

  }

 

const a = demofunction.call(undefined'10');

const b = demofunction.call(undefinedfalse);


In this example, checks the correct argument of the function and give the error.


  • If you create a project or workspace using the -strict option, then the package.json file is automatically created in the app folder. To enable a webpack to remove unnecessary modules in your project using the strict mode, the package.json file have a single property sideEffects set to false.

{

  "name""angular-strict",

  "private"true,

 

  "description_1""This is a special package.json file that is not used by package managers.",

 

  "description_2""It is used to tell the tools and bundlers whether the code under this directory is free of code with non-local side-effect. Any code that does have non-local side-effects can't be well optimized (tree-shaken) and will result in unnecessary increased payload size.",

 

  "description_3""It should be safe to set this option to 'false' for new applications, but existing code bases could be broken when built with the production config if the application code does contain non-local side-effects that the application depends on.",

 

  "description_4""To learn more about this file see: https://angular.io/config/app-package-json.",

 

  "sideEffects"false

}

  • Configures Tslint rules to prevent declarations of type any. Disallows usages of any as a type declaration. If you are dealing with data of any type, you can’t able to access members of it.

 "no-any": true,


We can use “ignore-rest-args” inside the no-any property. This property is used to provide rest arguments that will be ignored.


"no-any": [true, {"ignore-rest-args": true}]


Conclusion


In the above blog, we discussed the angular strict mode with the template type checking option. With the help of the --strict option, there will be a few additional typescript compiler option and an angular compiler option that will be added in the file.


Author Bio:


Ajay Patel - Technical Director, IFour Technolab Pvt. Ltd. A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. Wish sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop and Mobile solutions and is heading the technical department at AngularJS Frontend Development Company – iFour Technolab Pvt. Ltd.

0 comments:

Post a Comment

If you have any question, please email me at durgtech@gmail.com