node/no-path-concat 限制
它的作用
禁止使用 __dirname 和 __filename 进行字符串拼接。
为什么这是不好的?
在 Node.js 中,__dirname 和 __filename 全局变量分别包含当前执行脚本文件的目录路径和文件路径。 有时开发者会尝试使用这些变量来创建指向其他文件的路径,例如:
js
var fullPath = __dirname + "/foo.js";然而,这种方式容易出错,因为它没有考虑不同操作系统使用不同的路径分隔符。正确的方式是使用 path.join() 或 path.resolve() 来创建跨平台的文件路径。
示例
此规则的 错误 代码示例:
js
const fullPath1 = __dirname + "/foo.js";
const fullPath2 = __filename + "/foo.js";
const fullPath3 = `${__dirname}/foo.js`;
const fullPath4 = `${__filename}/foo.js`;此规则的 正确 代码示例:
js
const fullPath1 = path.join(__dirname, "foo.js");
const fullPath2 = path.join(__filename, "foo.js");
const fullPath3 = __dirname + ".js";
const fullPath4 = __filename + ".map";
const fullPath5 = `${__dirname}_foo.js`;
const fullPath6 = `${__filename}.test.js`;如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["node"],
"rules": {
"node/no-path-concat": "error"
}
}bash
oxlint --deny node/no-path-concat --node-plugin