Repository navigation
perf: format #7950
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+2,852
−2,505
Merged
perf: format #7950
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| import type { Rule } from 'eslint' | ||
|
|
||
| declare const importOrder: Rule.RuleModule | ||
| export default importOrder |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| // 项目导入分组;无绑定导入、注释和可执行语句作为排序边界。 | ||
| import path from 'node:path' | ||
|
|
||
| const compare = (left, right) => (left < right ? -1 : left > right ? 1 : 0) | ||
| const frameworks = ['vue', 'vue-router', 'pinia'] | ||
|
|
||
| function groupOf(source, isType, filename) { | ||
| if (isType) return 1 | ||
| const resolved = source.startsWith('.') ? path.resolve(path.dirname(filename), source).replaceAll('\\', '/') : source | ||
| if (/(?:@\/|\/src\/)api\/enums(?:\/|\.|$)/.test(resolved)) return 2 | ||
| if (/(?:@\/|\/src\/)api\//.test(resolved)) return 3 | ||
| if (!source.startsWith('.') && !source.startsWith('@/')) return 0 | ||
| if (/^@\/permission(?:\/index(?:\.ts)?)?$/.test(source)) return 6 | ||
| if (source.startsWith('.') || /^@\/(?:components|layout|views|workflow-canvas|conversation-panel|assets)\//.test(source)) return 4 | ||
| return 5 | ||
| } | ||
|
|
||
| function renderImport(node, specifiers, isType, code) { | ||
| const prefix = isType ? 'import type ' : 'import ' | ||
| const defaults = specifiers.filter((specifier) => specifier.type !== 'ImportSpecifier') | ||
| const named = specifiers | ||
| .filter((specifier) => specifier.type === 'ImportSpecifier') | ||
| .sort((left, right) => compare(left.imported.name ?? left.imported.value, right.imported.name ?? right.imported.value)) | ||
| const bindings = defaults.map((specifier) => code.getText(specifier)) | ||
| if (named.length) { | ||
| const names = named.map((specifier) => | ||
| specifier.importKind === 'type' ? code.getText(specifier).replace(/^type\s+/, '') : code.getText(specifier), | ||
| ) | ||
| const singleLine = `{ ${names.join(', ')} }` | ||
| const length = prefix.length + [...bindings, singleLine].join(', ').length + code.getText(node.source).length + 6 | ||
| // 与 .prettierrc.json 的 printWidth 保持一致。 | ||
| bindings.push(length > 150 ? `{\n${names.map((name) => ` ${name},`).join('\n')}\n}` : singleLine) | ||
| } | ||
| return `${prefix}${bindings.join(', ')} from ${code.getText(node.source)}${code.text.slice(node.source.range[1], node.range[1])}` | ||
| } | ||
|
|
||
| export default { | ||
| meta: { | ||
| type: 'layout', | ||
| fixable: 'code', | ||
| schema: [], | ||
| messages: { order: '按框架、类型、枚举、API、组件与功能、公共模块、perm 的顺序整理导入。' }, | ||
| }, | ||
| create(context) { | ||
| const code = context.sourceCode | ||
| function check(nodes) { | ||
| if (!nodes.length) return | ||
| const entries = nodes.flatMap((node) => { | ||
| // 带内部注释的声明原样保留,避免改变注释的作用对象。 | ||
| if (code.getCommentsInside(node).length) { | ||
| return [ | ||
| { source: node.source.value, group: groupOf(node.source.value, node.importKind === 'type', context.filename), text: code.getText(node) }, | ||
| ] | ||
| } | ||
| const types = node.specifiers.filter((specifier) => node.importKind === 'type' || specifier.importKind === 'type') | ||
| const values = node.specifiers.filter((specifier) => !types.includes(specifier)) | ||
| return [ | ||
| [types, true], | ||
| [values, false], | ||
| ] | ||
| .filter(([specifiers]) => specifiers.length) | ||
| .map(([specifiers, isType]) => ({ | ||
| source: node.source.value, | ||
| group: groupOf(node.source.value, isType, context.filename), | ||
| text: renderImport(node, specifiers, isType, code), | ||
| })) | ||
| }) | ||
| entries.sort((left, right) => { | ||
| if (left.group !== right.group) return left.group - right.group | ||
| if (left.group === 0) { | ||
| const rank = (source) => (frameworks.includes(source) ? frameworks.indexOf(source) : frameworks.length) | ||
| if (rank(left.source) !== rank(right.source)) return rank(left.source) - rank(right.source) | ||
| } | ||
| if (left.group === 4 && left.source.startsWith('@/') !== right.source.startsWith('@/')) return left.source.startsWith('@/') ? -1 : 1 | ||
| return compare(left.source, right.source) | ||
| }) | ||
| const replacement = entries.map((entry) => entry.text).join('\n') | ||
| const range = [nodes[0].range[0], nodes.at(-1).range[1]] | ||
| if (code.text.slice(...range) !== replacement) { | ||
| context.report({ node: nodes[0], messageId: 'order', fix: (fixer) => fixer.replaceTextRange(range, replacement) }) | ||
| } | ||
| } | ||
| return { | ||
| Program(program) { | ||
| let block = [] | ||
| for (const node of program.body) { | ||
| // 仅含 inline type 的值导入在 verbatimModuleSyntax 下仍会执行模块。 | ||
| // 保留声明及位置,避免拆分后丢失初始化副作用。 | ||
| const inlineTypesOnly = | ||
| node.type === 'ImportDeclaration' && | ||
| node.importKind !== 'type' && | ||
| node.specifiers.length > 0 && | ||
| node.specifiers.every((specifier) => specifier.importKind === 'type') | ||
| const previous = block.at(-1) | ||
| const gap = previous ? code.text.slice(previous.range[1], node.range[0]) : '' | ||
| const leadingComment = | ||
| node.type === 'ImportDeclaration' && code.getCommentsBefore(node).some((comment) => comment.loc.end.line >= node.loc.start.line - 1) | ||
| // 不跨越声明、初始化、样式导入或注释调整模块执行次序。 | ||
| if (node.type !== 'ImportDeclaration' || !node.specifiers.length || inlineTypesOnly || leadingComment || gap.trim()) { | ||
| check(block) | ||
| block = [] | ||
| } | ||
| if (node.type === 'ImportDeclaration' && node.specifiers.length && !inlineTypesOnly && !leadingComment) { | ||
| const trailingComment = code.getCommentsAfter(node).some((comment) => comment.loc.start.line === node.loc.end.line) | ||
| if (trailingComment) { | ||
| check(block) | ||
| block = [] | ||
| } else block.push(node) | ||
| } | ||
| } | ||
| check(block) | ||
| }, | ||
| } | ||
| }, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review of the ESLint rule (import grouping/sorting)
Bugs / Correctness issues
specifiers.filter((s) => !types.includes(s))is O(n²) —Array.prototype.includesontypesis linear. For imports this is negligible, butnew Set(types)or a simplespecifier.importKind !== 'type'predicate is cleaner. More importantly, in an inline mixed import (e.g.import { A, type B } from 'x'), splitting into twoimportlines changes semantics only mildly — but the split path runs whennode.importKind !== 'type', and the resulting value statement keeps all non-type specifiers. That's fine, but the emittedrenderImport(node, values, false, …)reusescode.getText(node.source)and slices trailing text fromnode.source.range[1]tonode.range[1]. If the original had a semicolon after the source (no assertions), that works; if it had import attributes / assertions (assert { type: 'json' }) they are preserved by the slice — good. However the same slice is applied to both the type sub-import and the value sub-import, so an attribute clause would end up duplicated onto the type import (which is illegal). Worth guarding.inlineTypesOnlydetection vs.typesfilter inconsistency. Incheck, you decide "all specifiers are type" per-node withnode.importKind === 'type' || specifier.importKind === 'type'. InProgram,inlineTypesOnlyusesnode.type === 'ImportDeclaration'while elsewhere you consistently testnode.type === 'ImportDeclaration'. Then later againif (node.type === 'ImportDeclaration' && …). Minor redundancy, not a bug. But the comment says such imports are kept in place to preserve side effects — yetgroupOffor a pureimport typenode returns group 1 regardless of whether the source is external/relative. So aimport typefrom./localwill be sorted among other type imports before runtime imports. That matches most conventions; just confirm intent.length > 150magic number. The comment says it mirrors.prettierrc.json printWidth, but 150 is hard-coded. If prettier config changes, this silently diverges. Better to read it once (or at least define a named constantconst PRINT_WIDTH = 150).Length calculation is approximate.
prefix.length + [...bindings, singleLine].join(', ').length + code.getText(node.source).length + 6— the+ 6accounts for' from 'and';'?' from 'is 6 chars, yes, plus possibly a trailing;on another line. This approximation ignores the trailing slice (attributes, comments). For typical cases it's fine; for correctness, compute against the fully rendered string instead:and check
candidate.length > PRINT_WIDTH.compare(left.imported.name ?? left.imported.value, …)doesn't handleImportNamespaceSpecifier/ImportDefaultSpecifierinnamed— those never appear there because of the filter, so it's fine, butleft.importedmay be undefined forimport { type Foo }where the middle AST differs across parsers (ImportSpecifier.importedis always present, so OK). Still,?? ''fallback would be safer.sourceregexes assume@/and/src/without an anchor. For instancesome-lib/src/api/foo(a published package with asrcfolder reused verbatim) would land in group 3. Rare but possible. Consider anchoring one segment less aggressively or documenting.path.resolve(...).replaceAll('\\', '/')—path.resolverequiresfilenameto be absolute;context.filenameis, so fine. But resolving aliases like@/api/enumscannot go throughpath.resolve(it produces nonsense paths). The subsequent regex still matches the literal@/api/enums, so behavior is unaffected — but theresolvedvalue is misleading. Split alias handling from relative handling for clarity.leadingCommentcheck usescomment.loc.end.line >= node.loc.start.line - 1. That treats a comment on the previous line as attached even if separated by a blank line (blank line should de-attach). Also, comments have already been used to reset the block viagap.trim()— if there's a comment in the gap,gap.trim()is non-empty, soleadingCommentis effectively redundant there except for the case where the comment sits between the import and the previous statement with no other text. Simplify: rely ongap.trim().trailingCommentfor the block boundary. On a trailing same-line comment youcheck(block)andblock = [], then push nothing — meaning the current node starts a fresh block but is never pushed. Next iteration,previousis undefined, sogapis'', treating the next import as adjacent. This can produce wrong grouping across the commented import. Should be:As written, after a trailing-comment import, the following import becomes the start of a new block spanning from that import onwards — which loses the commented import entirely from ordering. Whether intended (freeze position) or not, document it.
range = [nodes[0].range[0], nodes.at(-1).range[1]]— this replaces the whole span including inter-import blank lines. Sinceentries.map(text).join('\n')emits no blank lines, deliberate blank-line groupings between imports are destroyed. Most format-preserving rules re-emit with one blank line between groups. Confirm this is desired; otherwise you're fighting Prettier/dev expectations.node.specifiers.lengthguard — bareimport 'x.css'resets the block. Good, but a side-effect import between otherwise-sortable imports means the sort is never re-established after it. Consider starting a fresh block after it (push nothing, then continue — butpreviousmust beundefinedso the gap check restarts). Currently that's exactly what happens becauseblock=[]; fine.Type-only default imports:
import type Foo from 'x'—defaultsincludesFoo, but the specifier'simportKindis'value'on the specifier itself (parser moves it to node level). Fine. Butimport { type A }where entire list is type triggersinlineTypesOnly, skipping sort — intentional but silently skips these; add a comment.Missing
importKind === 'typeof'handling (TS pre-verbatim syntax). Low risk under modern TS.Repeated calls to
code.getText(specifier)/code.getText(node.source)within loops — cheap butrenderImportrecomputescode.getText(node.source)twice. Store once.typein meta is'layout'. Valid, but import ordering is usually'suggestion'; both work. Formeta.messages, adding an English message alongside is optional — enterprise lint configs often require i18n consistency; the Chinese message is consistent here.No
docsfield inmeta. Add at least{ description }for tooling/introspection.Schema empty array — fine, but if
printWidthwere made configurable, schema would need updating.The fix only reports on
nodes[0]. If a fix fails repeatedly ESLint disables autofix for the file. Fine, but multiplereportentries per problematic block would give clearer errors. Optional.Style / minor
flatMapproducing arrays of objects is fine; readability could be improved by extracting the "split into type/value pair" logic.permbut the sorting regex targets/^@\/permission/. Consistency: rename comment to match, e.g. "permission".frameworks.indexOf(source)inside sort → memoize with aMapfor clarity (trivial perf)._entry.textjoins with'\n'while original may use\r\non Windows (code.textis raw). Consider normalizing or joining with the detected EOL from the first node's line break.Summary of recommended fixes (priority order)
PRINT_WIDTHsrc/apiregex not to match third-party pathsdocs, memoized framework rank, remove redundantnode.type === 'ImportDeclaration'guardsOverall the rule logic is solid and defensively guards execution order — the main real risks are the trailing-comment block reset and the loss of intentional blank-line grouping.