Use ESLint to disallow projects from importing specific modules

Project team members want to be able to disable certain JS dependencies. For example, some team members want to use LoDash and introduce this huge dependency into the project, resulting in a bloated project. Team members should use Lodash-es to avoid this situation. ESLint then provides a rule called no-restricted-imports, which is a dependency that the uniform specification prohibits in a project.

Method of use

Full configuration rule

Assuming we don’t want to introduce Lodash into the project, the configuration rule is:

rules: {
    'no-restricted-imports': [
        'error',
        {
            paths: [{
                name: 'lodash'.message: 'Don't use Lodash, use Lodash-es instead'}}}]]Copy the code

If a team member tries to introduce the lodash dependency

import _ from 'lodash'

An error is reported and a message is prompted

No prompt message is required

If no prompt is required, message can be omitted as follows:

'no-restricted-imports': ['error', 'lodash', 'underscore']

Use the gitignore-style notation

'no-restricted-imports': ['error', {
    patterns: ['lodash-es/*']}]Copy the code

If the rule is violated, the following error message will appear:

reference

Eslint.org/docs/rules/…