Repository navigation
perf: format #7949
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
Closed
+2,852
−2,505
Closed
perf: format #7949
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 Findings
Potential Issues / Bugs
replaceAll('\\', '/')compatibility —String.prototype.replaceAllrequires Node ≥ 15 / modern runtimes. If this ESLint plugin targets older environments, use.split('\\').join('/')or a global regex. Depends on your engine range.Duplicate import merging semantics — When splitting a mixed type/value declaration into two, the reported fix replaces only the import block range. But if two original declarations for the same source existed (e.g., one value + one type), you emit two separate import statements that remain adjacent but not merged. That's fine for correctness, but be aware duplicate specifiers across type/value imports of the same module are preserved, which
no-duplicate-imports(or itsincludeExports) may flag elsewhere.Length estimate in
renderImportis approximate.The
+ 6magic number assumesfrom(6 chars) plus spaces; and thenode.sourcetext uses original quote style. This can misdecide multiline vs single-line near the boundary. Consider computing the actual rendered string first, then deciding:Also the
150threshold hardcodes Prettier'sprintWidthrather than reading config; acceptable if documented, but brittle if.prettierrcchanges.types.includes(specifier)— O(n²) but harmless for small specifier lists; using aSetwould be marginally cleaner.node.importKind === 'type' || specifier.importKind === 'type'— Correct, but note groupOf'sisTypehandling: for a mixed declaration you split into two entries wheregroupOf(..., true, ...)always returns group 1. Meaning all type-only imports go to group 1 regardless of source category. Likely intentional (types grouped separately) — confirm it matches your ordering rules.inlineTypesOnlydetection is incomplete. A declaration likeimport { type A, B }whereBis a value hasevery(... importKind === 'type')false — correct, untouched. But a declaration with zero specifiers (side-effect import, e.g.import './styles.css') is excluded by the!node.specifiers.lengthguard — good (comment mentions styles). OK.gap.trim()used as "don't cross boundaries" check — Comments attached between imports via blank lines break blocks; also any whitespace-only gap clears the block, so imports separated by blank lines are never reordered relative to each other. That may be stricter than desired; if users expect sorting across blank-line-separated groups, this silently disables it. Document this behavior or make it configurable.previousrecomputed within loop —block.at(-1)is read before possibly resettingblock; fine sincegapuses the pre-resetprevious. But logic flow is subtle: aftercheck(block); block = [], the same node is then pushed at the end if valid. Verify that whenleadingCommentis true, node is correctly excluded from all blocks (it is, since push is guarded by!leadingComment).No
context.filenamefallback —context.filenamewas added in ESLint 8.40 (replacingcontext.getFilename()). Fine if that's your minimum ESLint, otherwise add fallback.Report location
nodes[0]— Reports on the first import, but fixes whole block. Acceptable; consider reporting at the mismatched entry for clearer UX, orloc: { start: nodes[0].range[0], end: ... }.Missing
meta.docs/meta.hasSuggestions— Meta lacksdocs(url/description/recommended) — optional but conventional.Chinese message / English everything else — Minor consistency nit.
Optimization Suggestions
groupOfwith URL-prefix checks where possible; regexes like/(?:@\/|\/src\/)api\/enums(?:\/|\.|$)/will also match@/api/enums-old? No — the(?:\/|\.|$)guards prevent that. Good. But they're evaluated per import; caching bysourcecould help on large files.path.resolve+replaceAllper external-looking source is only invoked for non-.sources — actuallyresolvedcomputes for all sources including bare packages, callingpath.resolveneedlessly. Sinceresolvedis only used in the twoapiregexes meant for project paths, you can skip resolution for bare module specifiers (not starting with.or@/). Minor perf win.entries.sortcomparator covers groups 0 and 4 specially; note group 4 also falls through tocompare(source)after the@/rank, correct. For group 0 (frameworks), after rank comparison, non-framework packages sort alphabetically — verify you don't want framework sub-path imports (e.g.vue/dist/..., unlikely) grouped with their package; onlineincludesexact match meansvue-routerranks in the array whilevue-somethinggoes to alphabetical fallback. Fine but worth noting.Summary
Logic is generally sound and carefully guards comment/side-effect cases. Main actionable items: (a) make the width decision based on actual rendered string instead of the
+6heuristic, (b) confirmcontext.filename/replaceAllmatch your supported runtime, (c) consider surfacing the blank-line boundary behavior in docs, (d) minor cleanups (Set,docs, locale consistency).