Eslint未识别默认参数赋值中const变量的使用问题
问题:ESLint无法识别函数默认参数中使用的外部变量
代码示例
const prefDateFormat = { weekday: 'long', day: 'numeric', month: 'long' } function formatDates(dates, dateFormat = prefDateFormat){ ... }
ESLint报错信息
error 'prefDateFormat' is assigned a value but never used no-unused-vars
环境信息
- ESLint版本:
^6.7.2 - .eslintrc.js配置:
module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin:vue/vue3-essential', 'eslint:recommended' ], parserOptions: { parser: 'babel-eslint' }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off' }, overrides: [ { files: [ '**/__tests__/*.{j,t}s?(x)', '**/tests/unit/**/*.spec.{j,t}s?(x)' ], env: { jest: true } } ] }
提问
请问是否有办法让ESLint识别默认参数赋值中的变量使用?
解决方案
你可以通过以下几种方式解决这个问题:
1. 升级ESLint版本
ESLint v6.x的no-unused-vars规则存在识别缺陷,无法正确检测到函数默认参数中对外部变量的引用。升级到v7及以上版本后,这个问题会被修复,无需额外配置就能正常识别变量的使用场景。
2. 修改ESLint规则配置(不升级版本的情况下)
在.eslintrc.js的rules中,为no-unused-vars添加varsIgnorePattern选项,指定忽略该变量的未使用检查:
rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-unused-vars': ['error', { 'varsIgnorePattern': 'prefDateFormat' }] }
这种方式适合暂时无法升级ESLint的场景,精准忽略特定变量的检查。
3. 使用单行注释临时忽略
在prefDateFormat变量定义的行上方添加注释,跳过该行的no-unused-vars检查:
/* eslint-disable-next-line no-unused-vars */ const prefDateFormat = { weekday: 'long', day: 'numeric', month: 'long' }
这种方式适合临时处理单个变量的情况,不会影响全局规则。
内容的提问来源于stack exchange,提问作者Dimitris Papazacharias
相关产品推荐
相关产品推荐

