javascript.lang.best-practice.lazy-load-module.lazy-load-module

profile photo of semgrepsemgrep
Author
308
Download Count*

Lazy loading can complicate code bundling if care is not taken, also requires are run synchronously by Node.js. If they are called from within a function, it may block other requests from being handled at a more critical time. The best practice is to require modules at the beginning of each file, before and outside of any functions.

Run Locally

Run in CI

Defintion

rules:
  - id: lazy-load-module
    patterns:
      - pattern: require(...)
      - pattern-inside: |
          function $NAME(...) {
              ...
          }
    message: Lazy loading can complicate code bundling if care is not taken, also
      `require`s are run synchronously by Node.js. If they are called from
      within a function, it may block other requests from being handled at a
      more critical time. The best practice is to `require` modules at the
      beginning of each file, before and outside of any functions.
    languages:
      - javascript
      - typescript
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - javascript
      references:
        - https://nodesecroadmap.fyi/chapter-2/dynamism.html
        - https://github.com/goldbergyoni/nodebestpractices#-38-require-modules-first-not-inside-functions
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

lazy-load-module.js

// ok: lazy-load-module
const fs = require('fs')

function smth() {
  // ruleid: lazy-load-module
  const mod = require('module-name')
  return mod();
}