Skip to content

Commit

Permalink
report conditional require in a if block
Browse files Browse the repository at this point in the history
  • Loading branch information
Xiaoji Chen committed Aug 4, 2019
1 parent ebcf17c commit 147b74c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/rules/no-commonjs.js
Expand Up @@ -25,6 +25,11 @@ function allowRequire(node, options) {
return options.allowRequire
}

function validateScope(scope) {
if (scope.variableScope.type === 'module') return true
return false
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -87,7 +92,7 @@ module.exports = {

},
'CallExpression': function (call) {
if (context.getScope().type !== 'module') return
if (!validateScope(context.getScope())) return
if (
call.parent.type !== 'ExpressionStatement'
&& call.parent.type !== 'VariableDeclarator'
Expand Down
9 changes: 9 additions & 0 deletions tests/src/rules/no-commonjs.js
Expand Up @@ -56,6 +56,9 @@ ruleTester.run('no-commonjs', require('rules/no-commonjs'), {
{ code: 'module.exports = function () {}', options: [{ allowPrimitiveModules: true }] },
{ code: 'module.exports = "foo"', options: ['allow-primitive-modules'] },
{ code: 'module.exports = "foo"', options: [{ allowPrimitiveModules: true }] },

{ code: 'if (typeof window !== "undefined") require("x")', options: [{ allowRequire: true }] },
{ code: 'if (typeof window !== "undefined") { require("x") }', options: [{ allowRequire: true }] },
],

invalid: [
Expand All @@ -65,6 +68,12 @@ ruleTester.run('no-commonjs', require('rules/no-commonjs'), {
{ code: 'var x = require("x")', errors: [ { message: IMPORT_MESSAGE }] },
{ code: 'x = require("x")', errors: [ { message: IMPORT_MESSAGE }] },
{ code: 'require("x")', errors: [ { message: IMPORT_MESSAGE }] },
{ code: 'if (typeof window !== "undefined") require("x")',
errors: [ { message: IMPORT_MESSAGE }],
},
{ code: 'if (typeof window !== "undefined") { require("x") }',
errors: [ { message: IMPORT_MESSAGE }],
},
]),

// exports
Expand Down

0 comments on commit 147b74c

Please sign in to comment.