Skip to content

noDynamicNamespaceImportAccess

诊断类别:lint/nursery/noDynamicNamespaceImportAccess

¥Diagnostic Category: lint/nursery/noDynamicNamespaceImportAccess

自从:v1.9.0

¥Since: v1.9.0

禁止动态访问命名空间导入。

¥Disallow accessing namespace imports dynamically.

动态访问命名空间导入可以防止有效的树摇动并增加包大小。发生这种情况的原因是,打包器无法确定在编译时使用了命名空间的哪些部分,因此它必须在打包包中包含整个命名空间。

¥Accessing namespace imports dynamically can prevent efficient tree shaking and increase bundle size. This happens because the bundler cannot determine which parts of the namespace are used at compile time, so it must include the entire namespace in the bundle.

相反,请考虑使用命名导入,如果无法做到这一点,请静态访问命名空间导入属性。

¥Instead, consider using named imports or if that is not possible access the namespaced import properties statically.

如果你想完全禁止命名空间导入,请考虑使用 noNamespaceImport 规则。

¥If you want to completely disallow namespace imports, consider using the noNamespaceImport rule.

¥Examples

¥Invalid

import * as foo from "foo"
foo["bar"]
code-block.js:2:1 lint/nursery/noDynamicNamespaceImportAccess ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Avoid accessing namespace imports dynamically, it can prevent efficient tree shaking and increase bundle size.

1 │ import * as foo from “foo”
> 2 │ foo[“bar”]
^^^^^^^^^^
3 │

Prefer static property access or use named imports instead.

import * as foo from "foo"
const key = "bar"
foo[key]
code-block.js:3:1 lint/nursery/noDynamicNamespaceImportAccess ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Avoid accessing namespace imports dynamically, it can prevent efficient tree shaking and increase bundle size.

1 │ import * as foo from “foo”
2 │ const key = “bar”
> 3 │ foo[key]
^^^^^^^^
4 │

Prefer static property access or use named imports instead.

¥Valid

import * as foo from "foo"
foo.bar
import { bar } from "foo"
bar
import messages from "i18n"
const knownMessagesMap = {
hello: messages.hello,
goodbye: messages.goodbye
}
const dynamicKey = "hello"
knownMessagesMap[dynamicKey]

¥Related links