Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put import type always as last one with eslint-plugin-import

I have a react native project in which I use absolute paths starting with components/ features/ or infrastructure/

I wanted them to be separated from the node modules imports but I want to

import type {xxx} from 'features|components|infrastructure|';

to always go last within a group, or even better to all the import type to always go last in the entire imports section and preferably sorted alphabetically.

So far I came up with such a config

module.exports = {
  root: true,
  extends: ['@react-native-community'],
  plugins: ['import'],
  rules: {
    'import/order': [
      'error',
      {
        groups: [
          ['builtin', 'external'],
          'internal',
          'parent',
          ['sibling', 'index'],
          'object',
          'type',
        ],
        pathGroups: [
          {
            pattern: '@(react|react-native)',
            group: 'external',
            position: 'before',
          },
          {
            pattern: 'components/**',
            group: 'internal',
          },
          {
            pattern: 'features/**',
            group: 'internal',
          },
          {
            pattern: 'infrastructure/**',
            group: 'internal',
          },
        ],
        pathGroupsExcludedImportTypes: ['react'],
        'newlines-between': 'always',
        alphabetize: {
          order: 'asc',
          caseInsensitive: true,
        },
      },
    ],
  },
};

but the problem here is that it does not separate import and import type and it puts imports like so

import React from 'react';
import { View } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';

import RegistrationScreen from 'features/account/screens/Registration';
import type { Test } from 'features/account/types';
import { colors } from 'infrastructure/theme';

Thanks.

like image 600
seven Avatar asked Oct 24 '25 16:10

seven


2 Answers

Use groups and put type in the end

"import/order": [
  "error",
  {
    groups: ["builtin", "external", "internal", "parent", "sibling", "index", "object", "type"],
  },
],
like image 153
ViktorMS Avatar answered Oct 27 '25 05:10

ViktorMS


I was able to achieve it by including type in the pathGroupsExcludedImportTypes option. This tells the plugin to exclude type imports from path groups.

pathGroupsExcludedImportTypes: [
  'builtin',
  'object',
  'type',
],
like image 42
Hinrich Avatar answered Oct 27 '25 05:10

Hinrich