Skip to content

Commit

Permalink
unbreak try catch use case
Browse files Browse the repository at this point in the history
  • Loading branch information
Xiaoji Chen committed Aug 4, 2019
1 parent 147b74c commit a7c63d9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
19 changes: 14 additions & 5 deletions src/rules/no-commonjs.js
Expand Up @@ -30,6 +30,18 @@ function validateScope(scope) {
return false
}

// https://github.com/estree/estree/blob/master/es5.md
function isConditional(node) {
if (
node.type === 'IfStatement'
|| node.type === 'TryStatement'
|| node.type === 'LogicalExpression'
|| node.type === 'ConditionalExpression'
) return true
if (node.parent) return isConditional(node.parent)
return false
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -93,11 +105,6 @@ module.exports = {
},
'CallExpression': function (call) {
if (!validateScope(context.getScope())) return
if (
call.parent.type !== 'ExpressionStatement'
&& call.parent.type !== 'VariableDeclarator'
&& call.parent.type !== 'AssignmentExpression'
) return

if (call.callee.type !== 'Identifier') return
if (call.callee.name !== 'require') return
Expand All @@ -110,6 +117,8 @@ module.exports = {

if (allowRequire(call, options)) return

if (isConditional(call.parent)) return

// keeping it simple: all 1-string-arg `require` calls are reported
context.report({
node: call.callee,
Expand Down
10 changes: 4 additions & 6 deletions tests/src/rules/no-commonjs.js
Expand Up @@ -58,7 +58,11 @@ ruleTester.run('no-commonjs', require('rules/no-commonjs'), {
{ 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: false }] },
{ code: 'if (typeof window !== "undefined") { require("x") }', options: [{ allowRequire: true }] },
{ code: 'if (typeof window !== "undefined") { require("x") }', options: [{ allowRequire: false }] },

{ code: 'try { require("x") } catch (error) {}', options: [{ allowRequire: false}] },
],

invalid: [
Expand All @@ -68,12 +72,6 @@ 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 a7c63d9

Please sign in to comment.