noGlobalDirnameFilename
Summary
Section titled Summary- Diagnostic Category:
lint/nursery/noGlobalDirnameFilename
- This rule has a safe fix.
- The default severity of this rule is information.
- Sources:
- Inspired from
unicorn/prefer-module
- Inspired from
Description
Section titled DescriptionDisallow the use of __dirname
and __filename
in the global scope.
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
Section titled ExamplesInvalid
Section titled Invalidconst dirname = __dirname;
code-block.js:1:17 lint/nursery/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/nursery/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/nursery/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/nursery/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
Section titled Validconst dirname = import.meta.dirnameconst filename = import.meta.filenameconst foo = {__filename: import.meta.filename };if (import.meta.dirname.startsWith("/project/src/")) {}
How to configure
Section titled How to configure{ "linter": { "rules": { "nursery": { "noGlobalDirnameFilename": "error" } } }}