@digitak/grubber

中文文档
3.1.4发布于 2023/01/21MITTypeScriptES Module零依赖近 30 天下载 21万

Parse code files and patch it without having to use an AST

原始使用文档
文档目录5 节
  1. How?
  2. Installation
  3. Grubber API
  4. Using grubber with one of the preset languages
  5. Using grubber with custom rules

Grubber is a lightweight and friendly utility to parse code with regular expressions in a 100% safe way - without having to use an AST 🐛

In a higher level, Grubber also exposes helper functions to parse the dependencies of a file in many languages (Javascript, Typescript, Css, Scss, Python, Rust, C / C++, Nim, ...).

How?

The problem with parsing a source file with regular expressions is that you cannot be sure your match is not commented or inside a string.

For example, let's say you are looking for all const statements in a Javascript file - you would use a regular expression similar to:

/\bconst\s+/g;

But what if the file you want to parse is something like:

const x = 12;
// const y = 13;
let z = "const ";

Then you would match three const when only one should be matched.

Grubber understands what is a string, what is a comment and what is code so that you can overcome the issue very easily:

import { grub } from "@digitak/grubber";

const content = `
const x = 12
// const y = 13
let z = "const "
`;

const results = grub(content).find(/\bconst\s+/);
console.log(results.length); // will print 1 as expected

For the sake of the demonstration we used a simple regex, but remember that Ecmascript is a tricky language! Effectively finding all const statements would require a more refined regex. Ex: foo.const = 12 would be matched. Languages that use semi-colon at the end of every statement or strict indentation are much easier to parse in a 100% safe way.

Installation

Use your favorite package manager:

npm install @digitak/grubber

Grubber API

Grubber exports one main function grub:

export function grub(
    source: string,
    languageOrRules: LanguageName | Rule[] = "es",
): {
    // find one or more expressions and return an array of fragments
    find: (...expressions: Array<string | RegExp>) => Fragment[];

    // replace one or more expressions and return the patched string
    replace: (
        ...fromTos: Array<{
            from: string | RegExp;
            to: string | RegExp;
        }>
    ) => string;

    // find all dependencies (ex: `imports` in Typescript, `use` in Rust)
    findDependencies: () => Fragment[];

    // replace all dependencies by the given value
    // you can use special replace patterns like "$1" to replace
    // with the first captured group
    replaceDependencies: (to: string) => string;
};

The find and findDependencies methods both return an array of fragments:

export type Fragment = {
    slice: string; // the matched substring
    start: number; // start of the matched substring
    end: number; // end of the matched substring
    groups: string[] = []; // the captured groups
};

Using grubber with one of the preset languages

You can use any of the preset languages:

export type LanguageName =
    | "es" // Ecmascript (Javascript / Typescript / Haxe): the default
    | "rs" // Rust
    | "css"
    | "scss"
    | "sass"
    | "c"
    | "cpp"
    | "py" // Python
    | "nim";

Example:

// find all semi-colons inside the rust source code
grub(rustCodeToParse, "rs").find(";");

Using grubber with custom rules

You may define custom rules for the grubber parser, ie. what should be ignored an treated as "not code".

A Rule has the following type:

export type Rule =
    | {
            expression: string | RegExp; // the expression to ignore

            // if returns false, the match is ignored
            onExpressionMatch?: (match: RegExpExecArray) => boolean | void;
      }
    | {
            startAt: string | RegExp; // start of the expression to ignore
            stopAt: string | RegExp; // stop of the expression to ignore

            // if returns false, the match is ignored
            onStartMatch?: (match: RegExpExecArray) => boolean | void;
            onStopMatch?: (match: RegExpExecArray) => boolean | void;
      };

For example, the rules used for the C language are:

const rules: Rule[] = [
    {
        // string
        expression: /".*?[^\\](?:\\\\)*"/,
    },
    {
        // single line comment
        expression: /\/\/.*/,
    },
    {
        // multiline comment
        expression: /\/\*((?:.|\s)*?)\*\//,
    },
];

Rules are quite simple for most languages but get complicated for Ecmascript because of the ${...} syntax. Hopefully the job is already done for you!

🌿 🐛 🌿

版本与发布记录

@digitak/grubber 共发布 17 个版本,首次发布于 2021/04/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.1.4latest2023/01/213 年前
3.1.32022/08/174 年前
3.1.22022/06/164 年前
3.1.12022/01/194 年前
3.1.02022/01/194 年前
3.0.22021/12/144 年前

关于 @digitak/grubber 的常见问题

@digitak/grubber 是什么?

Parse code files and patch it without having to use an AST

如何安装 @digitak/grubber?

在项目目录运行 npm install @digitak/grubber,或使用 pnpm add / yarn add / bun add。

@digitak/grubber 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@digitak/grubber 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@digitak/grubber 可以商用吗?

@digitak/grubber 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@digitak/grubber 的下载量有多少?

根据 npm 官方下载统计,@digitak/grubber 在 2026/10/12 – 2026/11/10 这 30 天内被下载 209,861 次,日均约 6,995 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@digitak/grubber 还在维护吗?

最新版本 3.1.4 发布于 2023/01/21(3 年前);至今共发布 17 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/04/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。