Skip to content

Commit 108c1cd

Browse files
authored
Fix prefer-module-scope-constants in commonjs files (#460)
1 parent ef24642 commit 108c1cd

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

.changeset/brave-rice-reflect.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@shopify/eslint-plugin': minor
3+
---
4+
5+
Fix false positives for `prefer-module-scope-constants` rule in `*.cjs` files

packages/eslint-plugin/lib/rules/prefer-module-scope-constants.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ module.exports = {
3535
}
3636

3737
const scope = context.sourceCode.getScope(node);
38-
if (!['module', 'global'].includes(scope.type)) {
38+
39+
if (!isTopScope(scope)) {
3940
context.report(
4041
node,
4142
'You must place screaming snake case at module scope. If this is not meant to be a module-scoped variable, use camelcase instead.',
@@ -48,3 +49,19 @@ module.exports = {
4849
};
4950
},
5051
};
52+
53+
function isTopScope(scope) {
54+
if (['module', 'global'].includes(scope.type)) {
55+
return true;
56+
}
57+
58+
// CommonJS does not leak values outside of a given file. ESLint handles this
59+
// by claiming the whole file is wrapped in a function scope
60+
if (
61+
scope.upper.block.sourceType === 'commonjs' &&
62+
scope.upper.type === 'global'
63+
) {
64+
return true;
65+
}
66+
return false;
67+
}

packages/eslint-plugin/tests/lib/rules/prefer-module-scope-constants.test.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ const nonConstErrors = [
2020
];
2121

2222
const supportedLanguageOptions = [
23-
{parserOptions: {sourceType: 'module'}},
24-
{parserOptions: {sourceType: 'script'}},
23+
{sourceType: 'module'},
24+
{sourceType: 'script'},
25+
{sourceType: 'commonjs'},
2526
];
2627

2728
supportedLanguageOptions.forEach((languageOptions) => {

0 commit comments

Comments
 (0)