Understanding Treeshaking in Angular: A Guide to Optimizing Application Performance
Treeshaking is a process used by modern JavaScript bundlers to remove unused code (dead code) from an application during the build process. The goal of treeshaking is to reduce the size of the final bundle, which can improve the application's performance.
In the context of Angular, treeshaking is achieved through the use of the TypeScript compiler and the Angular compiler. TypeScript provides static type checking, and this information is used by the Angular compiler to determine which parts of the code are used and which are not. The Angular compiler then removes the unused code during the build process.
Here is an example of how to enable treeshaking in an Angular project:
1. Open the `tsconfig.json` file in the root of the Angular project.
2. Ensure the `"module"` option is set to `"es2022"`. This allows the TypeScript compiler to output code in the ECMAScript 2022 module format, which is necessary for treeshaking to work.
{
"compilerOptions": {
...
"module": "es2022",
...
}
}
3. In the `angular.json` file, ensure that the `optimization` option is set to `true` in the `build` configuration. This enables the Angular compiler to perform treeshaking during the build process.
{
...
"projects": {
"my-project": {
...
"architect": {
"build": {
...
"configurations": {
"production": {
"optimization": true,
...
}
}
}
}
}
}
}
4. Finally, ensure that the application code is written in a way that allows treeshaking to work effectively. This means avoiding side effects in modules, as well as using the `export` keyword to indicate which functions or classes should be used outside the module. Here's an example:
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
In this example, the `add` and `subtract` functions are exported, which indicates to the Angular compiler that they are used outside of the module. Any other functions or variables defined in the module that are not exported will be considered unused and will be removed during the treeshaking process.
Overall, treeshaking is an important optimization technique that can significantly reduce the size of an Angular application bundle. By enabling treeshaking and following best practices when writing application code, developers can improve application performance and provide a better user experience.
Or simply view the code on GitHub!