Using ESLint to restrict where files can be imported from

Published on in ESLint and JavaScript

There's an ESLint rule to prevent importing certain files in certain folders. I needed this in a multi-site project to prevent importing site-specific components in other sites' folders.

I'm talking about the no-restricted-paths ESLint rule, provided by the eslint-plugin-import plugin:

Some projects contain files which are not always meant to be executed in the same environment. For example consider a web application that contains specific code for the server and some specific code for the browser/client. In this case you don't want to import server-only files in your client code.

In my case I needed the rule to make using site-specific components more convenient. Context: Site-specific components in a multi-site (React) project.

Here's what I added to the project's ESLint config to solve the problem discussed in the linked blog post:

module.exports = {
  'import/no-restricted-paths': [
    'error',
    {
      zones: [
        {
          target: 'src/site-a/',
          from: 'src/common/Link.js',
          message: 'Import the site-specific Link component instead.',
        },
      ],
    },
  ],
}

The config makes ESLint throw an error if src/common/Link.js is imported in any file under src/site-a/. Plus ESLint will show the custom message so no one has to guess why importing the common Link component fails. Excellent!

To prevent importing certain npm packages, you could use ESLint's native rule no-restricted-imports. A useful example case is if you want developers to import your own Link component instead of React Router's Link component.