Angular - How to remove and avoid unused imports


Who else wants to remove unused imports from their Angular app? 🤔

A common cause of bloated Angular applications is unneeded imports.

And unused JavaScript packages & dependencies.

As an application grows, you can easily forget about the various dependencies our Angular app is using.

In our rush to launch and deliver it's possible to 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 way to do this. Type CTRL + SHIFT + P to open the command window and then search for Typescript: Remove Unused Imports.

But say, isn't there a better way to enforce this?

clean

How to enforce no unused imports

We can use an option called noUnusedLocals to throw an error if we have any imports that we aren't using.

Report errors on unused local variables. Source

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 remove unused imports and declarations from your Angular app.

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