evanw / evanw/esbuild

Plugin onTransform API

Open
#647 3 comments 20 reactions 0 assignees View on GitHub
plugins
Dominant language
Go
Stars
40.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

This proposes `onTransform`, a hook that runs transformations on a given file *after* the file has been loaded by a plugin or esbuild's default loader, and *before* any transformations done by esbuild itself

```ts
function onTransform (
opts: OnTransformOptions,
fn: (args: OnTransformArgs) => Promisable
): void;

interface OnTransformOptions {
filter: RegExp,
namespace?: string,
loader?: string,
}

interface OnTransformArgs {
path: string,
contents: string,
namespace: string,
loader: string,
}

interface OnTransformResult {
contents?: string | Uint8Array,
loader?: Loader,
resolveDir?: string,
errors?: Message[],
warnings?: Message[],
pluginName?: string,
}
```

The addition of `loader` in `OnTransformArgs` means that say, in a plugin that deals with CSS transforms, it wouldn't encounter JS source code whose filename ends with `.css`, and the plugin is also allowed to change the loader in the result if it encounters something like CSS modules and want to output the class name mappings

```ts
import postcss from 'postcss';

let processor = postcss([ /* plugins */ ]);

let postcssPlugin = {
name: 'postcss',
setup (build) {
build.onTransform({ filter: /.*/, loader: 'css' }, async (args) => {
let result = await processor.process(args.contents, { from: args.path });
// could do some other stuff here like mapping postcss' messages
// to esbuild's warnings and errors
return { contents: result.css };
});
},
};
```

Additionally it might be worthwhile to support passing sourcemaps in result, this should be useful for `onLoad` as well so this could probably go as a separate issue or something.

Contributor guide

No contributing guide indexed for this repository

Research direction

Review the proposed onTransform API, including its relationship to plugin onLoad behavior and the separate sourcemap suggestion. Compare the requested hook options, arguments, and results with the existing plugin API; done means the design is settled and the supported behavior is implemented and validated.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
build-system, tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.