You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置TypeScript+ESLint+Prettier实现命名规范及文件名校验

命名规范校验配置

@typescript-eslint/naming-convention 是 @typescript-eslint/eslint-plugin 内置的规则,你本地已经安装了对应依赖,不需要额外安装第三方包,直接在 .eslintrc.json 的 rules 字段添加配置即可:

"rules": {
  // 原有规则保留,新增以下内容
  "@typescript-eslint/naming-convention": [
    "error",
    // 类强制使用PascalCase命名
    {
      "selector": "class",
      "format": ["PascalCase"]
    },
    // 函数强制使用camelCase命名
    {
      "selector": "function",
      "format": ["camelCase"]
    },
    // 可选配置:方法名、变量统一使用camelCase
    {
      "selector": ["method", "variable"],
      "format": ["camelCase"]
    }
  ]
}

配置完成后你给出的示例代码中,nameExample_Foo 类、ThisIs_InValidName 方法都会触发错误提示。

文件名格式校验配置

文件名校验需要额外安装 eslint-plugin-check-file 依赖,执行安装命令:
npm install eslint-plugin-check-file -D

然后修改 .eslintrc.json 配置:

  1. 在 plugins 数组新增 check-file 项
  2. 在 rules 中添加对应文件名规则,以下示例要求所有.ts文件使用短横线命名(kebab-case):
"plugins": ["@typescript-eslint", "check-file"],
"rules": {
  // 原有规则保留,新增以下内容
  "check-file/filename-naming-convention": [
    "error",
    {
      "**/*.ts": "KEBAB_CASE"
    }
  ]
}

配置完成后你示例中的 foo_name.ts 会触发文件名格式错误。

注意事项

你当前配置存在ESLint和Prettier规则冲突:ESLint的quotes规则设置为双引号,而Prettier的singleQuote设置为true,二者冲突会导致自动修复时来回格式化,建议统一修改其中一项配置。

内容的提问来源于stack exchange,提问作者S. Wasta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:45:09