esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Make it possible to pass a function to define a plugin's onLoad filter attribute

Open DamienCassou opened this issue 5 months ago • 2 comments

I need to instrument part of my code base (with esbuild-plugin-istanbul) but this cannot be specified with a Go regex (e.g., I need to instrument all JS files except those ending with "Widget.js" and those in the tests/ directory).

The documentation for filters includes:

You should try to use the filter regular expression instead of using JavaScript code for filtering whenever you can.

When trying to use something else than a regexp, I get:

"filter" must be a RegExp object

so I'm unsure if functions are just discouraged or not implemented.

A similar feature was implemented in a PR that never received any attention: https://github.com/evanw/esbuild/pull/3667.

DamienCassou avatar Jul 23 '25 06:07 DamienCassou

I think you can just copy that plugin's source code (which is quite small!) and put additional filtering logic in the onLoad callback... for example:

    build.onLoad({ filter }, async (args) => {
      if (args.path.includes("node_modules")) return;
+     if (!args.path.endsWith('.js') || args.path.endsWith('Widget.js')) return;
+     if (args.path.includes('tests/')) return;
      const { contents: inCode } = await (preloader || defaultPreloader)(args);
      const outCode = nyc._transform(inCode, args.path) || inCode;
      return { contents: outCode, loader };
    });

hyrious avatar Jul 23 '25 09:07 hyrious

@hyrious that's the workaround I have implemented indeed.

DamienCassou avatar Jul 23 '25 18:07 DamienCassou