Einar  Hintz

Einar Hintz

1595345820

Code-splitting in Angular or how to share components between lazy modules

This article will give you a better understanding of how Angular split your code into chunks.

If you are scared from Angular CLI output showed above or if you’re curious how that code-splitting actually happens then this post is for you.

Code splitting allows you to split your code into various bundles which can then be loaded on demand. If used correctly, can have a major impact on load time.

Contents#

  1. Why should I care?
  2. Angular CLI code-splitting under the hood
  3. Simple Angular Application with lazy modules
  4. How to share components between lazy modules
  5. Conclusion

Why should I care?#

Let’s imagine you started a brand new Angular project. You read many resources on how to architect an Angular application, what is the appropriate folder structure and, what is most important, how to keep great startup performance.

You chose Angular CLI and created a modular application with lots of lazy-loaded feature modules. And of course, you created a shared module where you put commonly used directives, pipes, and components.

After a while, you caught yourself thinking that once your new feature module requires some functionality from other feature modules you tend to move this functionality to that single shared module.

The application evolves and soon you noticed that its startup time doesn’t meet your(and, most importantly, your client) expectation.

Now, you’re in doubts…

  • If I put all my pipes, directives and common components in one big shared module and then import it in lazy-loaded modules (where I use only one or two of the imported features) it probably may cause unused-code duplicates in the output files.
  • On the other hand, if I split shared features among several shared modules and import only those of them needed in every particular module will it reduce the size of my app? Or Angular does all such optimizations by default?

Let’s demystify!

Angular CLI code-splitting under the hood#

As we all know, the current Angular CLI version uses webpack to perform bundling. But despite that, webpack is also responsible for code-splitting.

So, let’s take a look at how webpack does it.

Webpack 4 introduced SplitChunksPlugin that allows us to define some heuristics to split modules into chunks. Many people complain that this configuration seems mysterious. And at the same time, this is the most interesting part of code splitting.

But before SplitChunksPlugin optimization is applied webpack creates a new chunk:

  • for every entry point

Angular CLI configures the following entry pointsmain

polyfills

styles

which will result in the chunks with the same names.

  • for every dynamically loaded module(by using [**import()**](https://webpack.js.org/api/module-methods/#import-1) syntax that conforms to the ECMAScript proposal for dynamic imports)

Do you remember loadChildren syntax? This is the signal for webpack to create a chunk.


Now let’s move on to the SplitChunksPlugin. It can be enabled inside optimizationblock of webpack.config.js

Let’s look at Angular CLI source code and find that configuration section:

#angular #performance #webpack

What is GEEK

Buddha Community

Code-splitting in Angular or how to share components between lazy modules
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Percy  Ebert

Percy Ebert

1592480580

Lazy Loading Angular Modules with Ivy

Angular Ivy makes it pretty easy to lazy load components, but what if we need to lazy load modules. Can we do that? In this article I’ll show you why you may need this and how it can be done.

#angular #angular-modules #lazy-loading #ivy

Einar  Hintz

Einar Hintz

1595345820

Code-splitting in Angular or how to share components between lazy modules

This article will give you a better understanding of how Angular split your code into chunks.

If you are scared from Angular CLI output showed above or if you’re curious how that code-splitting actually happens then this post is for you.

Code splitting allows you to split your code into various bundles which can then be loaded on demand. If used correctly, can have a major impact on load time.

Contents#

  1. Why should I care?
  2. Angular CLI code-splitting under the hood
  3. Simple Angular Application with lazy modules
  4. How to share components between lazy modules
  5. Conclusion

Why should I care?#

Let’s imagine you started a brand new Angular project. You read many resources on how to architect an Angular application, what is the appropriate folder structure and, what is most important, how to keep great startup performance.

You chose Angular CLI and created a modular application with lots of lazy-loaded feature modules. And of course, you created a shared module where you put commonly used directives, pipes, and components.

After a while, you caught yourself thinking that once your new feature module requires some functionality from other feature modules you tend to move this functionality to that single shared module.

The application evolves and soon you noticed that its startup time doesn’t meet your(and, most importantly, your client) expectation.

Now, you’re in doubts…

  • If I put all my pipes, directives and common components in one big shared module and then import it in lazy-loaded modules (where I use only one or two of the imported features) it probably may cause unused-code duplicates in the output files.
  • On the other hand, if I split shared features among several shared modules and import only those of them needed in every particular module will it reduce the size of my app? Or Angular does all such optimizations by default?

Let’s demystify!

Angular CLI code-splitting under the hood#

As we all know, the current Angular CLI version uses webpack to perform bundling. But despite that, webpack is also responsible for code-splitting.

So, let’s take a look at how webpack does it.

Webpack 4 introduced SplitChunksPlugin that allows us to define some heuristics to split modules into chunks. Many people complain that this configuration seems mysterious. And at the same time, this is the most interesting part of code splitting.

But before SplitChunksPlugin optimization is applied webpack creates a new chunk:

  • for every entry point

Angular CLI configures the following entry pointsmain

polyfills

styles

which will result in the chunks with the same names.

  • for every dynamically loaded module(by using [**import()**](https://webpack.js.org/api/module-methods/#import-1) syntax that conforms to the ECMAScript proposal for dynamic imports)

Do you remember loadChildren syntax? This is the signal for webpack to create a chunk.


Now let’s move on to the SplitChunksPlugin. It can be enabled inside optimizationblock of webpack.config.js

Let’s look at Angular CLI source code and find that configuration section:

#angular #performance #webpack

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

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

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular