Skip to content
← Back to rules

unicorn/prefer-import-meta-properties Pedantic

🛠️ An auto-fix is available for this rule.

作用

优先使用 import.meta.{dirname,filename},而不是使用传统 方式来获取文件路径。

为什么这不好?

从 Node.js 20.11 开始,import.meta.dirnameimport.meta.filename 已在 ES 模块中引入。 import.meta.filename 等价于 url.fileURLToPath(import.meta.url)import.meta.dirname 等价于 path.dirname(import.meta.filename)。 此规则会用 import.meta.dirnameimport.meta.filename 替换传统模式。

示例

以下是此规则的错误代码示例:

js
import path from "node:path";
import { fileURLToPath } from "url";

const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(fileURLToPath(import.meta.url));
const dirname = path.dirname(import.meta.filename);
const dirname = fileURLToPath(new URL(".", import.meta.url));

以下是此规则的正确代码示例:

js
const filename = import.meta.filename;
const dirname = import.meta.dirname;

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-import-meta-properties": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-import-meta-properties": "error",
  },
});
bash
oxlint --deny unicorn/prefer-import-meta-properties

版本

此规则于 v1.59.0 中添加。

参考资料