Eslint
规则 | Rules

no-restricted-modules

禁止 Node.js 模块(无限制模块)

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

你为什么要限制一个模块?

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

规则细节

这个规则允许你指定你不想在你的应用程序中使用的模块。

选项

规则采用一个或多个字符串作为选项:限制模块的名称。

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

它也可以带有一个包含pathsgitignore 风格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","loadash"限制模块:

/*eslint no-restricted-modules: ["error", "fs", "cluster"]*/ var fs = require('fs' var cluster = require('cluster'

/*eslint no-restricted-modules: ["error", {"paths": ["cluster"] }]*/ var cluster = require('cluster'

/*eslint no-restricted-modules: ["error", { "patterns": ["lodash/*"] }]*/ var pick = require('lodash/pick'

具有示例受限模块的此规则的正确代码示例"fs", "cluster","loadash"

/*eslint no-restricted-modules: ["error", "fs", "cluster"]*/ var crypto = require('crypto'

/*eslint no-restricted-modules: ["error", { "paths": ["fs", "cluster"], "patterns": ["lodash/*", "!lodash/pick"] }]*/ var crypto = require('crypto' var pick = require('lodash/pick'

版本

这条规则是在 ESLint 0.6.0 中引入的。

资源