You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过eslint-plugin-import让import type始终排在最后

解决ESLint import/order规则区分内部路径与type导入排序问题

问题分析

你当前的配置已经把components/、features/、infrastructure/归到internal组,但未区分普通导入和import type,导致type导入混在internal组中。要实现所有import type排在整个导入区域最后且按字母排序,需要针对type导入单独配置路径规则,并调整组的优先级顺序。

修改后的ESLint配置

module.exports = {
  root: true,
  extends: ['@react-native-community'],
  plugins: ['import'],
  rules: {
    'import/order': [
      'error',
      {
        groups: [
          ['builtin', 'external'],
          'internal',
          'parent',
          ['sibling', 'index'],
          'object',
          'type' // 将type组放在最后,确保所有类型导入处于整个导入区块末尾
        ],
        pathGroups: [
          // 优先排列react/react-native的外部导入
          {
            pattern: '@(react|react-native)',
            group: 'external',
            position: 'before',
            importType: 'value' // 指定匹配普通非type导入
          },
          // 内部路径的普通导入归到internal组
          {
            pattern: 'components/**',
            group: 'internal',
            importType: 'value'
          },
          {
            pattern: 'features/**',
            group: 'internal',
            importType: 'value'
          },
          {
            pattern: 'infrastructure/**',
            group: 'internal',
            importType: 'value'
          },
          // 内部路径的type导入单独归到type组
          {
            pattern: 'components/**',
            group: 'type',
            importType: 'type'
          },
          {
            pattern: 'features/**',
            group: 'type',
            importType: 'type'
          },
          {
            pattern: 'infrastructure/**',
            group: 'type',
            importType: 'type'
          }
        ],
        pathGroupsExcludedImportTypes: ['react'],
        'newlines-between': 'always',
        alphabetize: {
          order: 'asc',
          caseInsensitive: true
        }
      },
    ],
  },
};

配置说明

  1. 分组优先级调整:把type组移到所有组的最后,确保所有类型导入最终处于整个导入区块的末尾位置。
  2. 路径规则拆分:为每个内部路径分别配置两条规则:
    • importType: 'value':匹配普通的非type导入,归入internal组
    • importType: 'type':匹配import type导入,归入type组
  3. 字母排序生效:alphabetize配置会作用于所有组,包括type组,确保同组内的导入按字母顺序排列。

修正后的导入顺序示例

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

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

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

import type { Test } from 'features/account/types';

若存在多个type导入,会自动按字母顺序排列:

// 正确排序的type导入
import type { Account } from 'features/account/types';
import type { Theme } from 'infrastructure/theme';

内容的提问来源于stack exchange,提问作者seven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:56:07