首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

no-mixed-requires

在 Node.js 社区中,通常习惯将初始化与对require其他变量声明的模块调用分开,有时也将它们按模块类型分组。此规则可帮助您执行此惯例。

规则细节

当启用此规则时,每条var语句必须满足以下条件:

  • 无或全部变量声明都必须声明(默认)
  • 所有需要声明必须是相同类型(分组)

该规则区分了六种变量声明类型:

  • computed:声明所需模块的类型无法确定(或者是因为它是计算的,或者是因为 require 没有参数被调用)
  • uninitialized:未初始化的声明
  • other:任何其他类型的声明

在本文件中,头四种类型在术语需求声明下总结。

var fs = require('fs'),        // "core"     \
    async = require('async'),  // "module"   |- these are "require declaration"s
    foo = require('./foo'),    // "file"     |
    bar = require(getName()),  // "computed" /
    baz = 42,                  // "other"
    bam;                       // "uninitialized"

选项

此规则可以有一个对象字面量选项,其两个属性false默认具有值。

使用一个布尔选项配置此规则true已弃用。

此规则的默认选项的代码错误示例{ "grouping": false, "allowCall": false }

/*eslint no-mixed-requires: "error"*/

var fs = require('fs'),
    i = 0;

var async = require('async'),
    debug = require('diagnostics').someFunction('my-module'),
    eslint = require('eslint');

具有默认选项的此规则的正确代码示例{ "grouping": false, "allowCall": false }

/*eslint no-mixed-requires: "error"*/

// only require declarations (grouping off)
var eventEmitter = require('events').EventEmitter,
    myUtils = require('./utils'),
    util = require('util'),
    bar = require(getBarModuleName());

// only non-require declarations
var foo = 42,
    bar = 'baz';

// always valid regardless of grouping because all declarations are of the same type
var foo = require('foo' + VERSION),
    bar = require(getBarModuleName()),
    baz = require();

grouping

此规则的错误代码示例包含以下{ "grouping": true }选项:

/*eslint no-mixed-requires: ["error", { "grouping": true }]*/

// invalid because of mixed types "core" and "module"
var fs = require('fs'),
    async = require('async');

// invalid because of mixed types "file" and "unknown"
var foo = require('foo'),
    bar = require(getBarModuleName());

allowCall

此规则的错误代码示例包含以下{ "allowCall": true }选项:

/*eslint no-mixed-requires: ["error", { "allowCall": true }]*/

var async = require('async'),
    debug = require('diagnostics').someFunction('my-module'), /* allowCall doesn't allow calling any function */
    eslint = require('eslint');

此规则的正确代码示例包含以下{ "allowCall": true }选项:

/*eslint no-mixed-requires: ["error", { "allowCall": true }]*/

var async = require('async'),
    debug = require('diagnostics')('my-module'),
    eslint = require('eslint');

已知限制

  • 该实现不知道任何require可能影响 Node.js 全局的名称的本地函数require
  • 在内部,通过检索核心模块列表require("repl")._builtinLibs。如果您为 ESLint 和您的应用程序使用不同版本的 Node.js ,则每个版本的核心模块列表可能会有所不同。上述_builtinLibs属性在0.8中可用,对于早期版本,模块名称的硬编码列表被用作后备。如果您的 Node.js 版本早于0.6,那么列表可能不准确。

何时不使用它

如果使用 UMD 这样的模式,其中require d 模块未在变量声明中加载,则此规则显然对您不起作用。

版本

该规则在 ESLint 0.0.9 中引入。

资源

扫码关注腾讯云开发者

领取腾讯云代金券