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

如何让ESLint在Glob模式未匹配到文件时不报错?

解决方案

针对你遇到的ESLint在不存在目录时报错的问题,有以下几种无需新增脚本的解决方法:

方法一:使用ESLint内置选项(推荐)

ESLint从v7.0.0开始提供了--no-error-on-unmatched-pattern选项,开启后当glob模式匹配不到文件时,只会输出警告而非错误,直接避免报错。修改lintfixjs脚本即可:

"scripts": {
  "test": "yarn run lintfixjs && mocha --recursive",
  "lintfixjs": "eslint --fix --no-error-on-unmatched-pattern *.js tools/*.js other_tools/*.js lib/*.js"
}

该方法最简洁,只要项目中ESLint版本符合要求,开发者机器和服务器环境都能正常运行,无需额外shell逻辑。

方法二:Shell条件判断动态拼接参数

利用shell的目录存在性检查,动态决定是否添加对应的glob模式,确保ESLint只接收存在的路径:

"scripts": {
  "test": "yarn run lintfixjs && mocha --recursive",
  "lintfixjs": "eslint --fix *.js lib/*.js $(if [ -d tools ]; then echo 'tools/*.js'; fi) $(if [ -d other_tools ]; then echo 'other_tools/*.js'; fi)"
}

原理是:当tools或other_tools目录存在时,才将对应的glob参数传给ESLint;目录不存在时,这部分会输出空字符串,ESLint不会接收到无效模式。该方法兼容性好,无需依赖ESLint版本,适用于bash/zsh环境。

方法三:开启Shell的nullglob选项

在bash/zsh中开启nullglob选项后,匹配不到文件的glob模式会被直接移除,而非保留原样传递给ESLint:

"scripts": {
  "test": "yarn run lintfixjs && mocha --recursive",
  "lintfixjs": "shopt -s nullglob; eslint --fix *.js tools/*.js other_tools/*.js lib/*.js; shopt -u nullglob"
}

注意:shopt是bash专属命令,若服务器使用dash等其他shell,该方法可能不适用。

内容的提问来源于stack exchange,提问作者Darren Cook

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:52:48