Skip to content
jshacks.dev
Tooling

Ban specific imports with no-restricted-imports

Ban a single import such as lodash in favor of a lighter option, and ban one named export, with the no-restricted-imports rule in ESLint 9.

1 min read
Summarize in AI

no-restricted-imports can forbid a whole module, or one name from a module, and print your reason.

eslint.config.jsJavaScript
export default [
  {
    rules: {
      'no-restricted-imports': [
        'error',
        {
          paths: [
            { name: 'moment', message: 'Use Temporal or date-fns.' },
            {
              name: 'lodash',
              importNames: ['cloneDeep'],
              message: 'Use structuredClone.',
            },
          ],
        },
      ],
    },
  },
];
src/dates.jsJavaScript
import moment from 'moment';
import { cloneDeep, chunk } from 'lodash';
Text
src/dates.js
  1:1  error  'moment' import is restricted from being used. Use Temporal or date-fns.  no-restricted-imports
  2:10 error  'cloneDeep' import from 'lodash' is restricted. Use structuredClone.      no-restricted-imports

paths matches an exact module name, and importNames narrows it to chosen exports, so chunk stays allowed. This works well for a migration: block the old library for new code, and leave the existing call sites to be fixed over time. See the rule options.

Use patterns for globs. Dynamic import() and require calls are not covered by this rule, so add no-restricted-modules style checks through a plugin if you need them.

Taggedeslint
Share

More snippets

Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read
Tooling

Configure VS Code settings for a team

Share VS Code settings and recommended extensions with a team by committing a .vscode folder with settings.json and extensions.json.

1 min read
Tooling

Share an ESLint config across packages

Share one ESLint 9 flat config across workspace packages by exporting an array from a package and spreading it into each package's eslint.config.js.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.