Skip to content

Commit ada210b

Browse files
futpibljharb
authored andcommitted
Add allow-require option to no-commonjs rule
This fixes import-js#548
1 parent 48d0a8a commit ada210b

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

docs/rules/no-commonjs.md

+18
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,24 @@ module.exports = { a: "b" }
2121
exports.c = "d"
2222
```
2323

24+
### Allow require
25+
26+
If `allow-require` is provided as an option, `require` calls are valid:
27+
28+
```js
29+
/*eslint no-commonjs: [2, "allow-require"]*/
30+
31+
if (typeof window !== "undefined") {
32+
require('that-ugly-thing');
33+
}
34+
```
35+
36+
but `module.exports` is reported as usual.
37+
38+
This is useful for conditional requires.
39+
40+
### Allow primitive modules
41+
2442
If `allow-primitive-modules` is provided as an option, the following is valid:
2543

2644
```js

src/rules/no-commonjs.js

+7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ function allowPrimitive(node, context) {
1414
return (node.parent.right.type !== 'ObjectExpression')
1515
}
1616

17+
function allowRequire(node, context) {
18+
if (context.options.indexOf('allow-require') < 0) return false
19+
return true
20+
}
21+
1722
//------------------------------------------------------------------------------
1823
// Rule Definition
1924
//------------------------------------------------------------------------------
@@ -65,6 +70,8 @@ module.exports = {
6570
if (module.type !== 'Literal') return
6671
if (typeof module.value !== 'string') return
6772

73+
if (allowRequire(call, context)) return
74+
6875
// keeping it simple: all 1-string-arg `require` calls are reported
6976
context.report({
7077
node: call.callee,

tests/src/rules/no-commonjs.js

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ ruleTester.run('no-commonjs', require('rules/no-commonjs'), {
3737
{ code: "var bar = proxyquire('./bar');" },
3838
{ code: "var bar = require('./ba' + 'r');" },
3939
{ code: 'var zero = require(0);' },
40+
{ code: 'require("x")', options: ['allow-require'] },
4041

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

0 commit comments

Comments
 (0)