Want more? Subscribe to my free newsletter:

Disallow large imports from JavaScript projects

February 20, 2019

Are there known large JavaScript dependencies your team wish they could disallow from a project? Good news! ESLint supports disallowing specific imports from projects using the no-restricted-imports rule.

Below is an example using no-restricted-import to disallow importing moment.js (which could bloat your JavaScript bundle). The rule also supports custom messages, so an error can inform our team to try using the smaller date-fns or Luxon packages instead.

{
  "rules": {
    "no-restricted-imports": ["error", {
      "paths":  [{
        "name": "moment",
        "message": "Use date-fns or Luxon instead!"
      }]
    }]
  }
}

This would error and display our custom message if someone tried to:

import moment from 'moment';

Here's another example where we disallow importing all of lodash, favoring lodash-es:

{
  "rules": {
    "no-restricted-imports": ["error", {
      "name": "lodash",
      "message": "Use lodash-es instead!",
    }],
  }
}

Without a message, restricted imports can also be defined in an array-form:

{
  "rules": {
    "no-restricted-imports": ["error", "underscore", "bluebird"]
  }
}

For more advanced use-cases, no-restricted-imports supports an array of .gitignore-style patterns. Here, we error if someone attempts to import any modules matching the legacy/* pattern, like import helpers from 'legacy/helpers';:

{
  "rules": {
    "no-restricted-imports": ["error", {
        "patterns": ["legacy/*"]
    }],
  }
}

Authoring-time rules can be powerful for ensuring teams make consistent decisions about what they import into projects. To learn more, check out the official ESLint no-restricted-imports docs.

PS: Find ESLint useful? Consider a small donation to the lovely folks maintaining it.