Skip to content

Commit

Permalink
Add allow-require option to no-commonjs rule
Browse files Browse the repository at this point in the history
This fixes #548
  • Loading branch information
futpib committed Jun 23, 2017
1 parent 8101d39 commit d8dfc3b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
18 changes: 18 additions & 0 deletions docs/rules/no-commonjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@ module.exports = { a: "b" }
exports.c = "d"
```

### Allow require

If `allow-require` is provided as an option, `require` calls are valid:

```js
/*eslint no-commonjs: [2, "allow-require"]*/

if (typeof window !== "undefined") {
require('that-ugly-thing');
}
```

but `module.exports` is reported as usual.

This is useful for conditional requires.

### Allow primitive modules

If `allow-primitive-modules` is provided as an option, the following is valid:

```js
Expand Down
7 changes: 7 additions & 0 deletions src/rules/no-commonjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ function allowPrimitive(node, context) {
return (node.parent.right.type !== 'ObjectExpression')
}

function allowRequire(node, context) {
if (context.options.indexOf('allow-require') < 0) return false
return true
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -52,6 +57,8 @@ module.exports = {
if (module.type !== 'Literal') return
if (typeof module.value !== 'string') return

if (allowRequire(call, context)) return

// keeping it simple: all 1-string-arg `require` calls are reported
context.report({
node: call.callee,
Expand Down
1 change: 1 addition & 0 deletions tests/src/rules/no-commonjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ ruleTester.run('no-commonjs', require('rules/no-commonjs'), {
{ code: "var bar = proxyquire('./bar');" },
{ code: "var bar = require('./ba' + 'r');" },
{ code: 'var zero = require(0);' },
{ code: 'require("x")', options: ['allow-require'] },

{ code: 'module.exports = function () {}', options: ['allow-primitive-modules'] },
{ code: 'module.exports = "foo"', options: ['allow-primitive-modules'] },
Expand Down

0 comments on commit d8dfc3b

Please sign in to comment.