效果
能力
对导入的模块进行排序,排序后的代码看起来更整洁,外部库、公共组件、子组件、api、工具类依次排列。
规则配置
'import/order': [
'error',
{
// 对导入模块进行分组
groups: [
'builtin',
'external',
['internal', 'parent', 'sibling', 'index', 'object', 'type'],
'unknown'
],
// 通过路径自定义分组
pathGroups: [
{
// pattern:当前组中模块的最短路径匹配
pattern: '@app/**', // 在规定的组中选其一,index、sibling、parent、internal、external、builtin、object、type、unknown
group: 'external',
// 定义组的位置,after、before
position: 'after'
}
],
pathGroupsExcludedImportTypes: ['builtin'],
// newlines-between 不同组之间是否进行换行
'newlines-between': 'always',
// alphabetize 根据字母顺序对每个组内的顺序进行排序
alphabetize: {
order: 'asc',
caseInsensitive: true
}
}
]
group
是对导入模块进行分组。
// 1. node "builtin" modules
import fs from 'fs';
import path from 'path';
// 2. "external" modules
import _ from 'lodash';
import chalk from 'chalk';
// 3. "internal" modules
// (if you have configured your path or webpack to handle your internal paths differently)
import foo from 'src/foo';
// 4. modules from a "parent" directory
import foo from '../foo';
import qux from '../../foo/qux';
// 5. "sibling" modules from the same or a sibling's directory
import bar from './bar';
import baz from './bar/baz';
// 6. "index" of the current directory
import main from './';
// 7. "object"-imports (only available in TypeScript)
import log = console.log;
// 8. "type" imports (only available in Flow and TypeScript)
import type { Foo } from 'foo';
pathGroups
可以通过该配置设置别名,进行自定义路径分组。
属性
pattern
该组中模块的最短匹配路径(不会用于内置或外部)
patternOptions
最短匹配的选择,默认值:nocomment: true。即禁止将#开头的视为注释的行为。
group
在规定的组中选一个,pathGroup将相对于该组定位。
position
定义pathGroup将在组周围的位置,可以是“after”或“before”,如果未提供,则pathGroup将像组一样定位。
newlines-between
不同组之间是否进行换行。
[ignore|always|always-and-inside-groups|never]
-
如果设置为
ignore
,则不会报告与导入组之间的新行相关的错误。
-
如果设置为
always
,将强制每个组之间至少有一个新行,并且组内的新行将被禁止。为了防止导入之间出现多行,
no-multiple-empty-lines
可以使用核心规则。
-
如果设置为
always-and-inside-groups
,它将表现得像
always
导入组中允许换行符。
-
如果设置为
never
,则整个导入部分不允许换行。
alphabetize
根据字母顺序对每个组内的顺序进行排序。
-
order: 用于asc按升序排序,
desc用于按降序排序(默认值:ignore)。
-
orderImportKind: 用于asc按升序对各种导入类型进行排序,例如以typeor为前缀的typeof,具有相同的导入路径。用于desc按降序排序(默认值:)ignore。
-
caseInsensitive: 用于true忽略大小写,并false考虑大小写(默认值:false)。