unicorn/prefer-import-meta-properties
Require import.meta.dirname and import.meta.filename instead of building them from the URL
fixable
ES modules don't have __dirname or __filename, so a lot of code rebuilds them from import.meta.url with fileURLToPath() and path.dirname(). import.meta.filename and import.meta.dirname hold the same strings, with no imports.
--fix replaces the call with the property. It doesn't remove imports that are no longer used.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-import-meta-properties" = "error" # or "warn"Examples#
example.js2 problems
import path from "node:path";
import { fileURLToPath } from "node:url";
const filename = fileURLToPath(import.meta.url)Do not construct filename using fileURLToPath().;
const dirname = path.dirname(filename)Do not construct dirname.;example.js1 problem
import { fileURLToPath } from "node:url";
const dirname = fileURLToPath(new URL(".", import.meta.url))Do not construct dirname.;example.jsNo problems
const filename = import.meta.filename;
const dirname = import.meta.dirname;Other paths built from the URL are fine:
example.jsNo problems
import { fileURLToPath } from "node:url";
const fixtures = fileURLToPath(new URL("./fixtures", import.meta.url));When not to use it#
Bun has both properties, and Node.js has had them since 20.11. Turn the rule off for code that needs to run on an older Node.js.