no-import-assign

禁止分配给导入的绑定

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

ES 模块对导入绑定的更新会导致运行时错误。

¥The updates of imported bindings by ES Modules cause runtime errors.

规则详情

¥Rule Details

此规则警告导入绑定的分配、增量和减量。

¥This rule warns the assignments, increments, and decrements of imported bindings.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-import-assign: "error"*/

import mod, { named } from "./mod.mjs"
import * as mod_ns from "./mod.mjs"

mod = 1          // ERROR: 'mod' is readonly.
named = 2        // ERROR: 'named' is readonly.
mod_ns.named = 3 // ERROR: The members of 'mod_ns' are readonly.
mod_ns = {}      // ERROR: 'mod_ns' is readonly.
// Can't extend 'mod_ns'
Object.assign(mod_ns, { foo: "foo" }) // ERROR: The members of 'mod_ns' are readonly.

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-import-assign: "error"*/

import mod, { named } from "./mod.mjs"
import * as mod_ns from "./mod.mjs"

mod.prop = 1
named.prop = 2
mod_ns.named.prop = 3

// Known Limitation
function test(obj) {
    obj.named = 4 // Not errored because 'obj' is not namespace objects.
}
test(mod_ns) // Not errored because it doesn't know that 'test' updates the member of the argument.

何时不使用

¥When Not To Use It

如果你不想收到有关修改导入绑定的通知,你可以禁用此规则。

¥If you don’t want to be notified about modifying imported bindings, you can disable this rule.

由 TypeScript 处理

使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。

请注意,编译器不会捕获 Object.assign() 情况。因此,如果你在代码库中使用 Object.assign(),此规则仍然会提供一些值。

版本

此规则是在 ESLint v6.4.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号