版本

no-restricted-modules

当通过 require 加载时,禁用指定的模块

重要

此规则在 ESLint v7.0.0 中已弃用。请在 eslint-plugin-n 中使用相应的规则

了解更多

Node.js 中的模块是在 JavaScript 文件中组织的简单或复杂的功能,可以在整个 Node.js 应用程序中重用。关键字 require 在 Node.js/CommonJS 中用于将模块导入应用程序。这样,您可以进行动态加载,其中加载的模块名称不是预定义的/静态的,或者您仅在“真正需要”时有条件地加载模块。

为什么您要限制模块?

如果您想限制开发人员可以使用的可用方法,那么禁止使用特定的 Node.js 模块可能很有用。 例如,如果您想禁止文件系统访问,则可以阻止使用 fs 模块。

规则详情

此规则允许您指定您不想在应用程序中使用的模块。

选项

该规则接受一个或多个字符串作为选项:受限模块的名称。

"no-restricted-modules": ["error", "foo-module", "bar-module"]

它还可以接受一个对象,其中包含 paths 和 gitignore 样式的 patterns 字符串列表。

"no-restricted-modules": ["error", { "paths": ["foo-module", "bar-module"] }]
"no-restricted-modules": ["error", {
    "paths": ["foo-module", "bar-module"],
    "patterns": ["foo-module/private/*", "bar-module/*","!baz-module/good"]
}]

您还可以为您要限制的任何路径指定自定义消息,如下所示

"no-restricted-modules": ["error", {
  "name": "foo-module",
  "message": "Please use bar-module instead."
  }
]

或像这样

"no-restricted-modules": ["error",{
"paths":[{
  "name": "foo-module",
  "message": "Please use bar-module instead."
  }]
}]

自定义消息将附加到默认错误消息。请注意,您不能为受限模式指定自定义错误消息,因为特定模块可能匹配多个模式。

要限制所有 Node.js 核心模块的使用(通过 https://github.com/nodejs/node/tree/master/lib

{
    "no-restricted-modules": ["error",
        "assert","buffer","child_process","cluster","crypto","dgram","dns","domain","events","freelist","fs","http","https","module","net","os","path","punycode","querystring","readline","repl","smalloc","stream","string_decoder","sys","timers","tls","tracing","tty","url","util","vm","zlib"
    ]
}

示例

此规则的错误代码示例,其中示例 "fs", "cluster", "lodash" 是受限模块

在 Playground 中打开
/*eslint no-restricted-modules: ["error", "fs", "cluster"]*/

const fs = require('fs');
const cluster = require('cluster');
在 Playground 中打开
/*eslint no-restricted-modules: ["error", {"paths": ["cluster"] }]*/

const cluster = require('cluster');
在 Playground 中打开
/*eslint no-restricted-modules: ["error", { "patterns": ["lodash/*"] }]*/

const pick = require('lodash/pick');

此规则的正确代码示例,其中示例 "fs", "cluster", "lodash" 是受限模块

在 Playground 中打开
/*eslint no-restricted-modules: ["error", "fs", "cluster"]*/

const crypto = require('crypto');
在 Playground 中打开
/*eslint no-restricted-modules: ["error", {
    "paths": ["fs", "cluster"],
    "patterns": ["lodash/*", "!lodash/pick"]
}]*/

const crypto = require('crypto');
const pick = require('lodash/pick');

版本

此规则在 ESLint v0.6.0 中引入。

资源

更改语言