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

Node脚本中Glob的ignore选项相对路径问题

问题描述

项目结构

.
├── index.js
└── bootstrap/
    ├── css/
    │   ├── style.css
    │   └── fake.js
    └── js/
        └── index.js

预期效果与正确代码

想要查找bootstrap文件夹下所有JS文件,同时忽略css文件夹,以下代码符合预期:

index.js

const { globSync } = require('glob');

const files = globSync([`./bootstrap/**/*.js`], {
  ignore: [`bootstrap/css/**`],
});

files.forEach(file => {
  console.log(file); // outputs bootstrap/js/index.js
})

问题复现

但如果把ignore属性改为带./的相对路径:

ignore: [`./bootstrap/css/**`],

就无法排除css文件夹了,代码执行后会输出bootstrap/js/index.js和bootstrap/css/fake.js:

const { globSync } = require('glob');

const files = globSync([`./bootstrap/**/*.js`], {
  ignore: [`./bootstrap/css/**`],
});

files.forEach(file => {
  console.log(file); // outputs bootstrap/js/index.js and bootstrap/css/fake.js
})

请问问题出在哪里?为何ignore选项不能使用带./的相对路径?


问题原因与解决办法

核心原因是glob匹配生成的文件路径不会包含开头的./,而ignore规则是和最终匹配到的路径字符串做精确匹配校验的。

当你用globSync('./bootstrap/**/*.js')搜索时,返回的文件路径是bootstrap/js/index.js、bootstrap/css/fake.js这种不带./的格式。此时如果ignore规则写的是./bootstrap/css/**,规则里的路径前缀./和实际匹配到的路径开头不一致,自然无法匹配上,也就起不到排除作用。

反过来,当ignore规则用bootstrap/css/**时,和实际生成的文件路径前缀完全对应,就能正确匹配并排除css目录下的所有文件。

简单总结:glob输出的路径不带./,所以ignore规则也得用不带./的路径才能匹配生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:19:55