From f3e0581112ff29e9a07118368b1c9df43275a536 Mon Sep 17 00:00:00 2001 From: Chris Sauve Date: Fri, 22 Apr 2016 09:55:05 -0400 Subject: [PATCH] Make imports-first treat directives as an exception --- src/rules/imports-first.js | 21 ++++++++++++++++++--- tests/src/rules/imports-first.js | 9 +++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/rules/imports-first.js b/src/rules/imports-first.js index 8e044e6fb..790c81b7f 100644 --- a/src/rules/imports-first.js +++ b/src/rules/imports-first.js @@ -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)) { @@ -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++ } }) }, diff --git a/tests/src/rules/imports-first.js b/tests/src/rules/imports-first.js index 1733c3134..497387269 100644 --- a/tests/src/rules/imports-first.js +++ b/tests/src/rules/imports-first.js @@ -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';\ @@ -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 + }) + , ] })