eslint: False positive for global-require
Tell us about your environment
- ESLint Version: 4.0.0
- Node Version: 7.10.0
- npm Version: 5.0.3
What parser (default, Babel-ESLint, etc.) are you using? default
Please show your full configuration:
{
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"rules": {
"global-require": "error"
}
}
What did you do? Please include the actual source code causing the issue. This code is at the top level of the file:
var botVersion = process.env.npm_package_version || require('./package.json').version;
What did you expect to happen? I expect this code to work without warnings, as the statement is at the top level of the file. Notably, as the documentation of the global-require rule states, using a ternary operator instead gives no warnings:
var botVersion = process.env.npm_package_version ? process.env.npm_package_version : require('./package.json').version;
And the documentation for the no-unneeded-ternary rule asserts that using a logical OR operator should provide “the same functionality” as a ternary in this case.
What actually happened? Please include the actual, raw output from ESLint. ESLint gives a warning:
1:53 error Unexpected require() global-require
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 26 (23 by maintainers)
Lumping everything into
no-restricted-syntax
makes it really hard to configure in a shared config, because there’s no way to specify in JSON/YML that I want to add to the existing array of restricted syntaxes - which means I have to gather up and copy/paste the entire list from wherever it’s defined.It seems to me that this rule might be taking on too much responsibility. I think we should consider splitting this into two rules with ESLint 5.x:
require()
must be in global or module scope, i.e., not in a block or function scope. It does not care about how therequire()
is invoked.require()
calls cannot be in a ConditionalExpression or LogicalExpression.Would that make sense?
imo the bug is that it doesn’t also check ternaries.
If people want to allow module-level dynamic
require
s, I think that should be a separate rule (and this one disabled), or an option to this rule.Thank you for the report.
However, this works as intended. As https://github.com/eslint/eslint/issues/5773#issuecomment-205868680,
global-require
rule reportsrequire()
expressions which cannot be replaced by ES2015 Modules. So the rule disallows conditional importing.