Gavi
Gavi

Reputation: 1478

How to check for unused modules in Angular?

I'm working with Angular 9, and I've the following module declaration

const moduleRoutes: Routes = [
  {
    path: '',
    component: HomeComponent,
  }
];

@NgModule({
  declarations: [HomeComponent],
  providers: [HomeService],
  imports: [
    RouterModule.forChild(moduleRoutes),
    CommonModule,
    MatButtonModule,
    FlexLayoutModule,
    RouterModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatCheckboxModule,
    MatExpansionModule,
  ]
})
export class HomeModule {
}

How can I check if all the "imports" are needed? Is there a tool that can handle this task for me?

Upvotes: 8

Views: 6043

Answers (1)

Transformer
Transformer

Reputation: 7429

Good question, I had to do this myself, there are definitely tools out there to help you :)

  1. Option 1: npm install -g depcheck
  2. Option 2: yarn global add depcheck or if you are using Yarn
  3. CD over to the folder where you want your dependencies to be checked. Then run:

Bonus help

Many of the answers here are how to find unused items.

I wanted to remove them automatically.

  1. Install this node project:

    npm install -g typescript tslint tslint-etc

  2. At the root dir, add a new file tslint-imports.json:

    {
      "extends": [
        "tslint-etc"
      ],
      "rules": {
        "no-unused-declaration": true
      }
    }
    
  3. Run this at your own risk, make a backup :)

    tslint --config tslint-imports.json --fix --project .
    
    depcheck
    

https://www.npmjs.com/package/depcheck#usage

Upvotes: -3

Related Questions