Skip to main content

glob

项目地址

模块简介

glob 在正则出现之前就有了,主要用于匹配文件路径,例如大名鼎鼎的 gulp 就使用了 glob 规则来匹配、查找并处理各种后缀的文件。在前端工程化的过程中,不可避免地会用 Node.js 来读取文件,例如想找到 src 目录下所有 jsjsx 文件,代码应该怎么写呢?首先安装依赖包:

const glob = require('glob')
const files = glob.sync('src/**/*.js{,x}')
console.log(files)

加强版 globby

基础使用

安装

yarn add glob @types/glob

引入

  • Commonjs
const glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
  • ts
import glob from 'glob'


匹配语法

基础语法

/分隔符和片段

概念:分隔符是 /,通过 split('/') 得到的数组每一项是片段。

示例

  • src/index.js 有两个片段,分别是 srcindex.js
  • src/**/*.js 有三个片段,分别是 src***.js

*单个星号

概念:单个星号 * 用于匹配单个片段中的零个或多个字符。

示例

  • src/*.js 表示 src 目录下所有以 js 结尾的文件,但是不能匹配 src 子目录中的文件,例如 src/login/login.js
  • /home/*/.bashrc 匹配所有用户的 .bashrc 文件

注意

  • 需要注意的是,* 不能匹配分隔符 /,也就是说不能跨片段匹配字符。

?问号

概念:问号 ? 匹配单个片段中的单个字符。

示例

  • test/?at.js 匹配形如 test/cat.jstest/bat.js 等所有3个字符且后两位是 at 的 js 文件,但是不能匹配 test/flat.js
  • src/index.?? 匹配 src 目录下以 index 打头,后缀名是两个字符的文件,例如可以匹配 src/index.jssrc/index.md,但不能匹配 src/index.jsx

[]中括号

概念:同样是匹配单个片段中的单个字符,但是字符集只能从括号内选择,如果字符集内有 -,表示范围。

示例

  • test/[bc]at.js 只能匹配 test/bat.jstest/cat.js
  • test/[c-f]at.js 能匹配 test/cat.jstest/dat.jstest/eat.jstest/fat.js

!感叹号

概念:表示取反,即排除那些去掉惊叹号之后能够匹配到的文件。

示例

  • test/[!bc]at.js 不能匹配 test/bat.jstest/cat.js,但是可以匹配 test/fat.js
  • !test/tmp/**' 排除 test/tmp 目录下的所有目录和文件

拓展语法

基础语法非常简单好记,但是功能非常局限,为了丰富 glob 的功能,衍生了下面三种扩展语法:

**双星号

概念:两个星号 ** 可以跨片段匹配零个或多个字符,也就是说 ** 是递归匹配所有文件和目录的,如果后面有分隔符,即 **/ 的话,则表示只递归匹配所有目录(不含隐藏目录)。

示例

  • /var/log/** 匹配 /var/log 目录下所有文件和文件夹,以及文件夹里面所有子文件和子文件夹
  • /var/log/**/*.log 匹配 /var/log 及其子目录下的所有以 .log 结尾的文件
  • /home/*/.ssh/**/*.key 匹配所有用户的 .ssh 目录及其子目录内的以 .key 结尾的文件

{}大括号

概念:匹配大括号内的所有模式,模式之间用逗号进行分隔,支持大括号嵌套,支持用 .. 匹配连续的字符,即 {start..end} 语法。

示例

  • a.{png,jp{,e}g} 匹配 a.pnga.jpga.jpeg
  • {a..c}{1..2} 匹配 a1 a2 b1 b2 c1 c2

注意:

  • {}[] 有一个很重要的区别:如果匹配的文件不存在,[] 会失去模式的功能,变成一个单纯的字符串,而 {} 依然可以展开。

()小括号

概念:小括号必须跟在 ?*+@! 后面使用,且小括号里面的内容是一组以 | 分隔符的模式集合,例如:abc|a?c|ac*

示例

  • ?(pattern|pattern|pattern):匹配0次或1次给定的模式
  • *(pattern|pattern|pattern):匹配0次或多次给定的模式
  • +(pattern|pattern|pattern):匹配1次或多次给定的模式
  • @(pattern|pattern|pattern):严格匹配给定的模式
  • !(pattern|pattern|pattern):匹配非给定的模式

配置对象

语法:

import { glob, IOptions } from 'glob';

const pattern = ''
const opts:Ioption

glob(pattern, opts, callback)

Ioption

import type minimatch = require("minimatch");

declare namespace G {
interface IOptions extends minimatch.IOptions {
cwd?: string | undefined; // 工作目录
root?: string | undefined; // 根目录,用来替换匹配式的第一个反斜杠,匹配式需要 / 开始
dot?: boolean | undefined;
nomount?: boolean | undefined;
mark?: boolean | undefined;
nosort?: boolean | undefined;
stat?: boolean | undefined;
silent?: boolean | undefined;
strict?: boolean | undefined;
cache?: { [path: string]: boolean | 'DIR' | 'FILE' | ReadonlyArray<string> } | undefined;
statCache?: { [path: string]: false | { isDirectory(): boolean} | undefined } | undefined;
symlinks?: { [path: string]: boolean | undefined } | undefined;
realpathCache?: { [path: string]: string } | undefined;
sync?: boolean | undefined;
nounique?: boolean | undefined;
nonull?: boolean | undefined;
debug?: boolean | undefined;
nobrace?: boolean | undefined;
noglobstar?: boolean | undefined;
noext?: boolean | undefined;
nocase?: boolean | undefined;
matchBase?: any;
nodir?: boolean | undefined;
ignore?: string | ReadonlyArray<string> | undefined;
follow?: boolean | undefined;
realpath?: boolean | undefined;
nonegate?: boolean | undefined;
nocomment?: boolean | undefined;
absolute?: boolean | undefined;
fs?: typeof fs;
}
}
字段说明示例
cwd工作目录,对应Process.cwd'.'
root根目录,用来替换匹配式的第一个反斜杠,匹配式需要 / 开始'/**/*.md'
dot
nomount
mark
nosort
stat
silent
strict
cache
statCache
symlinks
realpathCache
sync
nounique
nonull
debug
nobrace
noglobstar
noext
nocase
matchBase
nodir
ignore
follow
realpath
nonegate
nocomment
absolute
fs

应用案例

批量创建文件

创建 a1.jsa9.jsb1.jsb9.js 这 18 个测试文件

$ touch {a,b}{1..9}.js
$ ls
a1.js a3.js a5.js a7.js a9.js b2.js b4.js b6.js b8.js
a2.js a4.js a6.js a8.js b1.js b3.js b5.js b7.js b9.js

webpack 多页面应用自动打包配置

在一个 webpack 项目中,假如我们有多个入口,每个入口都有一个 index.html 模板和 index.js 文件,而且这个入口是动态变化的,不希望每增加一个入口就改 webpack.config.js 配置文件,应该怎么办呢?

此时可以约定在 src 下面创建的文件夹,只要里面有 index.js,我们就把它当做一个入口文件进行打包:

src
├── detail
│ ├── index.html
│ └── index.js
├── home
│ ├── index.html
│ └── index.js
├── login
│ ├── index.html
│ └── index.js
├── shop
│ ├── index.html
│ └── index.js

用 glob 很快就能写出下面的自动打包代码:

const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const glob = require('glob')

// 动态生成 entry 和 html-webpack-plugin
function getMpa() {
const entry = {}, htmlPlugins = []
const files = glob.sync('src/*/index.js')
files.forEach((file) => {
const filename = file.split('/')[1]
entry[filename] = path.join(__dirname, file)
htmlPlugins.push(
new HtmlWebpackPlugin({
template: path.join(__dirname, `src/${filename}/index.html`),
filename: `${filename}.html`,
chunks: [filename],
})
)
})
return { entry, htmlPlugins }
}
const mpa = getMpa()

// 动态的配置文件
module.exports = {
entry: mpa.entry,
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]-[hash:6].js',
},
plugins: [...mpa.htmlPlugins],
}

这样,无论增加多少个入口,webpack.config.js 都不用变。

约定大于配置的框架/项目(egg)

egg.js 是一款优秀的 Node.js 企业级开发框架,就应用了约定大于配置的思想,例如:

  • 约定一个中间件是一个放置在 app/middleware 目录下的单独文件
  • 约定了 app/router.js 文件用于统一所有路由规则
  • 约定 Service 文件必须放在 app/service 目录,可以支持多级目录,访问的时候可以通过目录名级联访问

因为一个大规模的团队需要遵循一定的约束和约定,开发效率才更高,有了这些约定之后,我们就可以利用 glob 写出匹配规则,找到用户放到指定目录下的文件并进行动态加载了,一个最基础的 load 函数如下:

function load(folder, options) {
const extname = options.extname || '.{js,ts}'
return glob.sync(require('path').join(folder, `./**/*.js`)).forEach((item) => require(item))
}
复制代码

使用 glob,配合相应的规范,例如 RESTful,我们自己也能封装一个简易的、基于约定的 Node.js 框架了。