1 # Enforce require() on the top-level module scope (global-require)
3 This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
5 In Node.js, module dependencies are included using the `require()` function, such as:
8 var fs = require("fs");
11 While `require()` may be called anywhere in code, some style guides prescribe that it should be called only in the top level of a module to make it easier to identify dependencies. For instance, it's arguably harder to identify dependencies when they are deeply nested inside of functions and other statements:
17 var fs = require("fs");
22 Since `require()` does a synchronous load, it can cause performance problems when used in other locations.
24 Further, ES6 modules mandate that `import` and `export` statements can only occur in the top level of the module's body.
28 This rule requires all calls to `require()` to be at the top level of the module, similar to ES6 `import` and `export` statements, which also can occur only at the top level.
30 Examples of **incorrect** code for this rule:
33 /*eslint global-require: "error"*/
36 // calling require() inside of a function is not allowed
37 function readFile(filename, callback) {
38 var fs = require('fs');
39 fs.readFile(filename, callback)
42 // conditional requires like this are also not allowed
43 if (DEBUG) { require('debug'); }
45 // a require() in a switch statement is also flagged
46 switch(x) { case '1': require('1'); break; }
48 // you may not require() inside an arrow function body
49 var getModule = (name) => require(name);
51 // you may not require() inside of a function body as well
52 function getModule(name) { return require(name); }
54 // you may not require() inside of a try/catch block
56 require(unsafeModule);
62 Examples of **correct** code for this rule:
65 /*eslint global-require: "error"*/
67 // all these variations of require() are ok
71 z = require('z').initialize();
73 // requiring a module and using it in a function is ok
74 var fs = require('fs');
75 function readFile(filename, callback) {
76 fs.readFile(filename, callback)
79 // you can use a ternary to determine which module to require
80 var logger = DEBUG ? require('dev-logger') : require('logger');
82 // if you want you can require() at the end of your module
83 function doSomethingA() {}
84 function doSomethingB() {}
91 If you have a module that must be initialized with information that comes from the file-system or if a module is only used in very rare situations and will cause significant overhead to load it may make sense to disable the rule. If you need to `require()` an optional dependency inside of a `try`/`catch`, you can disable this rule for just that dependency using the `// eslint-disable-line global-require` comment.