Skip to content

Commit f3e0581

Browse files
committed
Make imports-first treat directives as an exception
1 parent e5480b7 commit f3e0581

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

Diff for: src/rules/imports-first.js

+18-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,24 @@
11
module.exports = function (context) {
2+
function isPossibleDirective (node) {
3+
return node.type === 'ExpressionStatement' &&
4+
node.expression.type === 'Literal' &&
5+
typeof node.expression.value === 'string'
6+
}
7+
28
return {
39
'Program': function (n) {
410
const body = n.body
511
, absoluteFirst = context.options[0] === 'absolute-first'
6-
let last = -1
12+
let nonImportCount = 0
13+
, anyExpressions = false
714
, anyRelative = false
8-
body.forEach(function (node, i){
15+
body.forEach(function (node){
16+
if (!anyExpressions && isPossibleDirective(node)) {
17+
return
18+
}
19+
20+
anyExpressions = true
21+
922
if (node.type === 'ImportDeclaration') {
1023
if (absoluteFirst) {
1124
if (/^\./.test(node.source.value)) {
@@ -17,12 +30,14 @@ module.exports = function (context) {
1730
})
1831
}
1932
}
20-
if (i !== ++last) {
33+
if (nonImportCount > 0) {
2134
context.report({
2235
node,
2336
message: 'Import in body of module; reorder to top.',
2437
})
2538
}
39+
} else {
40+
nonImportCount++
2641
}
2742
})
2843
},

Diff for: tests/src/rules/imports-first.js

+9
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ ruleTester.run('imports-first', rule, {
1111
export { x, y }" })
1212
, test({ code: "import { x } from 'foo'; import { y } from './bar'" })
1313
, test({ code: "import { x } from './foo'; import { y } from 'bar'" })
14+
, test({ code: "'use directive';\
15+
import { x } from 'foo';" })
16+
,
1417
],
1518
invalid: [
1619
test({ code: "import { x } from './foo';\
@@ -28,5 +31,11 @@ ruleTester.run('imports-first', rule, {
2831
, options: ['absolute-first']
2932
, errors: 1
3033
})
34+
, test({ code: "import { x } from 'foo';\
35+
'use directive';\
36+
import { y } from 'bar';"
37+
, errors: 1
38+
})
39+
,
3140
]
3241
})

0 commit comments

Comments
 (0)