使用 ESLint 禁止项目导入特定模块

使用 ESLint 禁止项目导入特定模块

项目团队成员但愿可以禁用某些 JS 依赖。好比有团队成员但愿使用 lodash 而将这个巨大的依赖引入项目,致使项目总体过度臃肿。团队成员应当使用 lodash-es 来避免这种状况。那么 ESLint 就提供了一个名为 no-restricted-imports 规则,这个规则就是统一规范在项目中禁止使用的依赖。git

20190303134710.png

使用方法

完整配置规则

假设咱们不但愿在项目中引入 lodash,那么配置规则:spa

rules: {
    'no-restricted-imports': [
        'error',
        {
            paths: [{
                name: 'lodash',
                message: '不要使用 lodash,请使用 lodash-es 做为替代'
            }]
        }
    ]
}

若是有团队成员试图引入 lodash 这个依赖3d

import _ from 'lodash'eslint

那么就会报错,并提示 message 信息rest

20190303135856.png

不须要显示提示信息

若是不须要显示任何提示信息,那么 message 能够被省略,写法以下:code

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

使用 gitignore-style 写法

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

若是违反规则会出现如下报错信息:rem

20190303140912.png

参考

https://eslint.org/docs/rules/no-restricted-importsunderscore

相关文章
相关标签/搜索