Skip to content

Commit

Permalink
Make imports-first treat directives as an exception
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed Apr 22, 2016
1 parent e5480b7 commit f3e0581
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/rules/imports-first.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
module.exports = function (context) {
function isPossibleDirective (node) {
return node.type === 'ExpressionStatement' &&
node.expression.type === 'Literal' &&
typeof node.expression.value === 'string'
}

return {
'Program': function (n) {
const body = n.body
, absoluteFirst = context.options[0] === 'absolute-first'
let last = -1
let nonImportCount = 0
, anyExpressions = false
, anyRelative = false
body.forEach(function (node, i){
body.forEach(function (node){
if (!anyExpressions && isPossibleDirective(node)) {
return
}

anyExpressions = true

if (node.type === 'ImportDeclaration') {
if (absoluteFirst) {
if (/^\./.test(node.source.value)) {
Expand All @@ -17,12 +30,14 @@ module.exports = function (context) {
})
}
}
if (i !== ++last) {
if (nonImportCount > 0) {
context.report({
node,
message: 'Import in body of module; reorder to top.',
})
}
} else {
nonImportCount++
}
})
},
Expand Down
9 changes: 9 additions & 0 deletions tests/src/rules/imports-first.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ ruleTester.run('imports-first', rule, {
export { x, y }" })
, test({ code: "import { x } from 'foo'; import { y } from './bar'" })
, test({ code: "import { x } from './foo'; import { y } from 'bar'" })
, test({ code: "'use directive';\
import { x } from 'foo';" })
,
],
invalid: [
test({ code: "import { x } from './foo';\
Expand All @@ -28,5 +31,11 @@ ruleTester.run('imports-first', rule, {
, options: ['absolute-first']
, errors: 1
})
, test({ code: "import { x } from 'foo';\
'use directive';\
import { y } from 'bar';"
, errors: 1
})
,
]
})

0 comments on commit f3e0581

Please sign in to comment.