How can I order imports module in an Angular standalone component?

52 Views Asked by At

I would like to have to order the imports in a standalone component based on the same rules more or less as the imports of the files. Let met explain.

For the imports on top of a *.ts file, I have an eslint rules that will allow me to Sort them and group them.

import/order": [
          "error",
          {
            "groups": [["builtin", "external"], "internal", ["parent", "sibling"], "index", "unknown"],
            "newlines-between": "always",
            "alphabetize": {
              /* sort in ascending order. Options: ["ignore", "asc", "desc"] */
              "order": "asc",
              /* ignore case. Options: [true, false] */
              "caseInsensitive": false
            }
          }
        ],

This allows me to sort my import on top

import { DOCUMENT } from '@angular/common';
import { AfterViewInit, Component, Inject } from '@angular/core';

import { someMethod } from '@internal/shared';

import { someMethodFromHelper } from './app.component.helper';

What I wish to do now, is to be able to sort the imports module of the component

Before:

@Component({
  standalone: true,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [],
  imports: [ 

    // unordered imports
    CommonModule,
    TranslocoModule,
    ProjectDetailsComponent,
    ClientComponent,
    ReactiveFormModule
  ]
})

After:

@Component({
  standalone: true,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [],
  imports: [ 

    // Ordered imports (by groups + alphabetical order)
    CommonModule,
    ReactiveFormModule,
    
    TranslocoModule,
    
    ClientComponent,
    ProjectDetailsComponent
  ]
})

I've look through the web without finding anything usefull on it. As anyone ever achieve this?

Thank in advance for any help !

1

There are 1 best solutions below

0
IDK4real On

What you wish to do is not standard behavior, so there is nothing on the web that allows for this.

Can it be done? Yes.

How? You would need to create a custom eslint rule to do it.