Angular - How to remove and avoid unused imports

Daniel Kreider
Daniel Kreider
Published on July 31st at 1:12pm
  • Angular Performance
  • Typescript
  • TSLint

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.

As an application grows, we developers tend to ignore all the dependencies. And we forget to check our imports to make sure we're not importing things we don't use.

So how do we avoid this?

How do we make sure that all unneeded and unused 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.

unused%20import%20error

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.

signature

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 un-used imports for your Angular application, and keep it lean, clean and healthy.

Unleash your skills