Angular - How to remove and avoid unused imports
Who else wants to avoid and get rid of those unused Typescript imports that you keep forgetting about? 🤔
A common cause of bloated Angular applications is unneeded imports.
And unused JavaScript dependencies.
As an application grows, we developers tend to forget about the various dependencies our Angular app is using. We forget to check our imports to make sure we're not importing JavaScript dependencies and libraries that we don't use.
So how do we avoid this?
How do we make sure that all unneeded and unused JavaScript and library imports are cleaned up?
Well...
Visual Code has a handy keyboard shortcut Alt + Shift + O
that you can use to automatically clean up a file.
But say, isn't there a better way to enforce this?
How to error if there are unused imports
We can use an option called noUnusedLocals
to throw an error if we have any imports that we aren't using.
Open the tsconfig.app.json
file in the root directory of your Angular application and add it to the compilerOptions section like this.
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"noUnusedLocals": true
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
Now, when I try to build my application with an unused import I'll get an error.
Cool?
Yeah. Cool!
Conclusion
And that, my friend, is how to make sure you never ship a bloated Angular project with unused imports.
This allows us to force a cleaner developer experience as well as a better code base.
Questions? Comments? Don't hesitate to reach out.
Angular Consultant
P.S - If you're one of those that skips to the end (like me) then this article will show you how to delete all the unused imports for your Angular application, and keep it lean, clean and healthy.
P.P.S - Are you struggling with Angular performance? Then I've created just what you need - The Complete Guide to Angular Performance.