Skip to content

Commit

Permalink
Add rule for const outside of module scope.
Browse files Browse the repository at this point in the history
Good:

```
const FOO = 'FOO';
export const BAR = 'BAR';
```

Bad:

```
function derp() {
  const FOO = 'FOO';
}

if (false) {
  const BLAH = 'BLAH';
}
```

---

I did not add configuration for this rule in the default preset (but I
can if we want it)...
  • Loading branch information
rwjblue committed Nov 21, 2015
1 parent 573bed9 commit 02f93c3
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/jscsrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"./rules/*.js"
],

"disallowConstOutsideModuleScope": true,

This comment has been minimized.

Copy link
@runspired

runspired Jan 12, 2016

@rwjblue per your comment in the commit, shouldn't this be false?

This comment has been minimized.

Copy link
@rwjblue

rwjblue Jan 12, 2016

Author Collaborator

Ya, but I changed it due to conversation in PR and didn't update commit message.

"disallowEmptyBlocks": true,
"disallowKeywordsOnNewLine": ["else"],
"disallowMultipleLineBreaks": true,
Expand Down
38 changes: 38 additions & 0 deletions lib/rules/disallow-const-outside-module-scope.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
var assert = require('assert');

module.exports = function() { };

module.exports.prototype = {
configure: function(option) {
assert(option === true, this.getOptionName() + ' requires a true value');
},

getOptionName: function() {
return 'disallowConstOutsideModuleScope';
},

check: function(file, errors) {
file.iterateNodesByType('VariableDeclaration', function(node) {
if (node.parentNode.type === 'Program') {
// declaration is in root of module
return;
}

if (node.parentNode.type === 'ExportNamedDeclaration' && node.parentNode.parentNode.type === 'Program') {
// declaration is a `export const foo = 'asdf'` in root of the module
return;
}

for (var i = 0; i < node.declarations.length; i++) {
var thisDeclaration = node.declarations[i];

if (thisDeclaration.parentNode.kind === 'const') {
errors.add(
'`const` should only be used in module scope (not inside functions/blocks).',
node.loc.start
);
}
}
});
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function something() {
const foo = 'bar';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if (true) {
const foo = 'bar';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const foo = 'blah';
export const bar = 'derp';

function something() {
let hey = 'you!';
}

0 comments on commit 02f93c3

Please sign in to comment.