noGlobalDirnameFilename
¥Summary
-
规则生效日期:
v2.0.0¥Rule available since:
v2.0.0 -
诊断类别:
lint/correctness/noGlobalDirnameFilename¥Diagnostic Category:
lint/correctness/noGlobalDirnameFilename -
此规则包含 safe 修复程序。
¥This rule has a safe fix.
-
此规则的默认严重级别为 information。
¥The default severity of this rule is information.
-
来源:
¥Sources:
-
¥Inspired from
unicorn/prefer-module
-
¥How to configure
{ "linter": { "rules": { "correctness": { "noGlobalDirnameFilename": "error" } } }}¥Description
禁止在全局作用域中使用 __dirname 和 __filename。
¥Disallow the use of __dirname and __filename in the global scope.
它们是 在 ES 模块中不可用。从 Node.js 20.11 开始,ES 模块中引入了 import.meta.dirname 和 import.meta.filename,其功能与 CommonJS (CJS) 中的 __dirname 和 __filename 完全相同。
¥They are not available in ES modules.
Starting with Node.js 20.11, import.meta.dirname and import.meta.filename have been introduced in ES modules, providing identical functionality to __dirname and __filename in CommonJS (CJS).
¥Examples
¥Invalid
const dirname = __dirname;code-block.js:1:17 lint/correctness/noGlobalDirnameFilename FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Don’t use __dirname.
> 1 │ const dirname = __dirname;
│ ^^^^^^^^^
2 │
ℹ __dirname is not available in ES modules.
ℹ Safe fix: Replace __dirname with import.meta.dirname.
1 │ - const·dirname·=·__dirname;
1 │ + const·dirname·=·import.meta.dirname;
2 2 │
const filename = __filename;code-block.js:1:18 lint/correctness/noGlobalDirnameFilename FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Don’t use __filename.
> 1 │ const filename = __filename;
│ ^^^^^^^^^^
2 │
ℹ __filename is not available in ES modules.
ℹ Safe fix: Replace __filename with import.meta.filename.
1 │ - const·filename·=·__filename;
1 │ + const·filename·=·import.meta.filename;
2 2 │
const foo = { __filename }code-block.js:1:15 lint/correctness/noGlobalDirnameFilename FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Don’t use __filename.
> 1 │ const foo = { __filename }
│ ^^^^^^^^^^^
2 │
ℹ __filename is not available in ES modules.
ℹ Safe fix: Replace __filename with import.meta.filename.
1 │ const·foo·=·{·__filename:·import.meta.filename·}
│ ++++++++++++++++++++++
if (__dirname.startsWith("/project/src/")) {}code-block.js:1:5 lint/correctness/noGlobalDirnameFilename FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Don’t use __dirname.
> 1 │ if (__dirname.startsWith(“/project/src/”)) {}
│ ^^^^^^^^^
2 │
ℹ __dirname is not available in ES modules.
ℹ Safe fix: Replace __dirname with import.meta.dirname.
1 │ - if·(__dirname.startsWith(“/project/src/”))·{}
1 │ + if·(import.meta.dirname.startsWith(“/project/src/”))·{}
2 2 │
¥Valid
const dirname = import.meta.dirnameconst filename = import.meta.filenameconst foo = {__filename: import.meta.filename };if (import.meta.dirname.startsWith("/project/src/")) {}¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号