Skip to content

noCommonJs

诊断类别:lint/nursery/noCommonJs

¥Diagnostic Category: lint/nursery/noCommonJs

自从:v1.9.0

¥Since: v1.9.0

来源:

¥Sources:

禁止使用 CommonJs 模块系统,转而使用 ESM 样式导入。

¥Disallow use of CommonJs module system in favor of ESM style imports.

ESM 样式 import 是 CommonJS require 导入的现代替代品。所有现代浏览器和 Node.js 版本均支持。与 CommonJs 相比,工具可以更轻松地静态分析和树状摇动 ESM import

¥ESM-style imports are modern alternative to CommonJS require imports. Supported by all modern browsers and Node.js versions. Tooling can more easily statically analyze and tree-shake ESM imports compared to CommonJs.

¥Examples

¥Invalid

require('node:fs');
code-block.js:1:1 lint/nursery/noCommonJs ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Use ESM imports instead of require.

> 1 │ require(‘node:fs ’);
^^^^^^^^^^^^^^^^^^
2 │

ESM-style import statements are more easily statically analyzable and tree-shakable compared to CommonJs require.

module.exports = { a: 'b' }
code-block.js:1:1 lint/nursery/noCommonJs ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Use ESM exports instead of module.exports.

> 1 │ module.exports = { a: ‘b’ }
^^^^^^^^^^^^^^
2 │

ESM-style export statements are more easily statically analyzable and tree-shakable compared to CommonJs module.exports.

exports.a = 'b';
code-block.js:1:1 lint/nursery/noCommonJs ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Use ESM exports instead of module.exports.

> 1 │ exports.a = ‘b’;
^^^^^^^^^
2 │

ESM-style export statements are more easily statically analyzable and tree-shakable compared to CommonJs module.exports.

¥Valid

import fs from 'node:fs';
import('node:fs')
export const a = 'b';
export default { a: 'b' };

¥Caveats

规则在 .cjs.cts 文件中自动禁用,因为它们明确是 CommonJs 文件。

¥Rule is automatically disabled inside .cjs and .cts files, because they are explicitly CommonJs files.

如果你正在从 CommonJs 迁移到 ESM,此规则可能会有所帮助,但如果你希望继续使用 CommonJs,则可以安全地禁用它。

¥This rule could be helpful if you are migrating from CommonJs to ESM, but if you wish to continue using CommonJs, you can safely disable it.

¥Related links