Skip to content

Commit d4f5526

Browse files
mysticateanzakas
authored andcommitted
Fix: vars-on-top crashs at export declarations (fixes #6210) (#6220)
1 parent 088bda9 commit d4f5526

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed

lib/rules/vars-on-top.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,23 @@ module.exports = {
4646
node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier";
4747
}
4848

49+
/**
50+
* Checks whether a given node is a variable declaration or not.
51+
*
52+
* @param {ASTNode} node - any node
53+
* @returns {boolean} `true` if the node is a variable declaration.
54+
*/
55+
function isVariableDeclaration(node) {
56+
return (
57+
node.type === "VariableDeclaration" ||
58+
(
59+
node.type === "ExportNamedDeclaration" &&
60+
node.declaration &&
61+
node.declaration.type === "VariableDeclaration"
62+
)
63+
);
64+
}
65+
4966
/**
5067
* Checks whether this variable is on top of the block body
5168
* @param {ASTNode} node - The node to check
@@ -64,9 +81,7 @@ module.exports = {
6481
}
6582

6683
for (; i < l; ++i) {
67-
if (statements[i].type !== "VariableDeclaration" &&
68-
(statements[i].type !== "ExportNamedDeclaration" ||
69-
statements[i].declaration.type !== "VariableDeclaration")) {
84+
if (!isVariableDeclaration(statements[i])) {
7085
return false;
7186
}
7287
if (statements[i] === node) {

tests/lib/rules/vars-on-top.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,40 @@ ruleTester.run("vars-on-top", rule, {
457457
sourceType: "module"
458458
},
459459
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
460+
},
461+
{
462+
code: [
463+
"import {foo} from 'foo';",
464+
"export {foo};",
465+
"var test = 1;"
466+
].join("\n"),
467+
parserOptions: {
468+
ecmaVersion: 6,
469+
sourceType: "module"
470+
},
471+
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
472+
},
473+
{
474+
code: [
475+
"export {foo} from 'foo';",
476+
"var test = 1;"
477+
].join("\n"),
478+
parserOptions: {
479+
ecmaVersion: 6,
480+
sourceType: "module"
481+
},
482+
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
483+
},
484+
{
485+
code: [
486+
"export * from 'foo';",
487+
"var test = 1;"
488+
].join("\n"),
489+
parserOptions: {
490+
ecmaVersion: 6,
491+
sourceType: "module"
492+
},
493+
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
460494
}
461495
]
462496
});

0 commit comments

Comments
 (0)