Skip to content
← Back to rules

unicorn/text-encoding-identifier-case 风格

An auto-fix is available for this rule.

它的作用

此规则强制对文本编码标识符采用一致的大写格式,具体包括:

  • 使用 'utf8' 而非 'UTF-8''utf-8'(如果启用了 withDash,则允许使用 'utf-8'
  • 使用 'ascii' 而非 'ASCII'

为什么这是不好的?

编码标识符大小写不一致会降低代码的可读性,并可能导致在整个代码库中产生细微的混淆。尽管 ECMAScript 或 Node.js 并未严格强制要求大小写,但使用小写字母是约定俗成且广泛认可的风格。

示例

此规则的错误代码示例:

javascript
import fs from "node:fs/promises";
async function bad() {
  await fs.readFile(file, "UTF-8");
  await fs.readFile(file, "ASCII");
  const string = buffer.toString("utf-8");
}

此规则的正确代码示例:

javascript
import fs from "node:fs/promises";
async function good() {
  await fs.readFile(file, "utf8");
  await fs.readFile(file, "ascii");
  const string = buffer.toString("utf8");
}

此规则在配置 { "withDash": true } 时的正确代码示例:

javascript
import fs from "node:fs/promises";
async function good() {
  await fs.readFile(file, "utf-8");
  await fs.readFile(file, "ascii");
  const string = buffer.toString("utf-8");
}

配置

此规则接受一个包含以下属性的配置对象:

withDash

type: boolean

默认值: false

如果为 true,则优先使用 utf-8 而非 utf8

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "unicorn/text-encoding-identifier-case": "error"
  }
}
bash
oxlint --deny unicorn/text-encoding-identifier-case

参考资料