Skip to content

Commit

Permalink
fix: disable sorting dynamic require imports
Browse files Browse the repository at this point in the history
  • Loading branch information
azat-io committed Jul 31, 2024
1 parent bff6575 commit 68632df
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
23 changes: 12 additions & 11 deletions rules/sort-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,15 +356,14 @@ export default createEslintRule<Options<string[]>, MESSAGE_ID>({
node.type === 'ImportDeclaration' ||
node.type === 'VariableDeclaration'
) {
let value =
node.type === 'ImportDeclaration'
? node.source.value
: (
(node.declarations[0].init as TSESTree.CallExpression)
.arguments[0] as TSESTree.Literal
)
.value!.toString()
.toString()
let value: string
if (node.type === 'ImportDeclaration') {
;({ value } = node.source)
} else {
let decl = node.declarations[0].init as TSESTree.CallExpression
let declValue = (decl.arguments[0] as TSESTree.Literal).value
value = declValue!.toString()
}

setCustomGroups(options.customGroups.value, value)

Expand Down Expand Up @@ -430,7 +429,8 @@ export default createEslintRule<Options<string[]>, MESSAGE_ID>({
}
} else {
let decl = node.declarations[0].init as TSESTree.CallExpression
name = (decl.arguments[0] as TSESTree.Literal).value!.toString()
let { value } = decl.arguments[0] as TSESTree.Literal
name = value!.toString()
}

nodes.push({
Expand All @@ -455,7 +455,8 @@ export default createEslintRule<Options<string[]>, MESSAGE_ID>({
node.declarations[0].init &&
node.declarations[0].init.type === 'CallExpression' &&
node.declarations[0].init.callee.type === 'Identifier' &&
node.declarations[0].init.callee.name === 'require'
node.declarations[0].init.callee.name === 'require' &&
node.declarations[0].init.arguments[0]?.type === 'Literal'
) {
registerNode(node)
}
Expand Down
20 changes: 20 additions & 0 deletions test/sort-imports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4575,5 +4575,25 @@ describe(ruleName, () => {
invalid: [],
},
)

ruleTester.run(`${ruleName}: ignores dynamic requires`, rule, {
valid: [
{
code: dedent`
const path = require(path);
const myFileName = require('the-filename');
const file = require(path.join(myDir, myFileName));
const other = require('./other.js');
`,
options: [
{
newlinesBetween: 'never',
groups: ['builtin', 'external', 'side-effect'],
},
],
},
],
invalid: [],
})
})
})

0 comments on commit 68632df

Please sign in to comment.