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

配置ESLint单引号后,VSCode保存自动转为双引号问题求助

保存代码时ESLint单引号规则不生效排查

问题场景

已通过.eslintrc.cjs配置ESLint强制使用单引号,VSCode的settings.json开启了保存时自动格式化及ESLint自动修复,但保存test.js文件时,代码中的单引号仍被自动转为双引号。

相关配置文件

.eslintrc.cjs

module.exports = {
  root: true,
  env: {
    browser: true,
    commonjs: true,
    es6: true,
    jest: true,
    node: true,
  },
  extends: [
    'eslint-config-react-app',
    'react-app',
  ],
  ignorePatterns: ['dist', '.eslintrc.cjs'],
  plugins: ['import'],
  rules: {
    quotes: [2, 'single'],
  },
  "globals": {
    "React": "readonly"
  }
}

VSCode settings.json

{
    "editor.tabSize": 2,
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
}

test.js 文件内容

export const Utils = {
  isFunction: function (it: any) {
    return toString.call(it) === '[object Function]';
  },
}

可能原因及解决方法

1. 格式化工具优先级冲突

VSCode的editor.formatOnSave默认调用内置格式化器或其他已安装的格式化插件(如Prettier),这些工具的引号规则可能与ESLint冲突,且执行顺序可能在ESLint修复之前,导致ESLint修复后的单引号又被转成双引号。

解决方法:

  • 让ESLint接管格式化:在settings.json中设置默认格式化器为ESLint插件:
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
    
  • 若使用Prettier,需统一规则:安装eslint-config-prettier和eslint-plugin-prettier,在.eslintrc.cjs的extends中添加'plugin:prettier/recommended',同时在Prettier配置文件(如.prettierrc)中设置:
    {
      "singleQuote": true
    }
    

2. ESLint规则被预设覆盖或未适配TS语法

你的test.js文件中使用了TypeScript类型标注(it: any),但当前ESLint配置未启用TypeScript相关规则,普通的quotes规则可能无法处理TS语法场景;另外,eslint-config-react-app预设可能包含了更高优先级的引号规则(如@typescript-eslint/quotes),覆盖了你自定义的quotes规则。

解决方法:

  • 安装TypeScript ESLint插件:npm install @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev
  • 修改.eslintrc.cjs,配置TS解析器和插件,并使用TS版本的引号规则:
    module.exports = {
      // 其他配置不变
      parser: '@typescript-eslint/parser',
      plugins: ['import', '@typescript-eslint'],
      rules: {
        '@typescript-eslint/quotes': [2, 'single'],
      },
    }
    
  • 建议将test.js重命名为test.ts,确保ESLint正确识别为TS文件。

3. VSCode ESLint插件未正确激活

检查VSCode右下角是否显示ESLint图标,若未显示,可能是插件未激活或未检测到ESLint配置。

解决方法:

  • 重新加载VSCode(快捷键Ctrl+Shift+P -> 选择"Reload Window")
  • 确保项目根目录已安装ESLint依赖(npm install eslint --save-dev)

内容的提问来源于stack exchange,提问作者Dg Foo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:07:31