Skip to content

Plugin onTransform API #647

Open
Open
@intrnl

Description

@intrnl

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

function onTransform (
  opts: OnTransformOptions,
  fn: (args: OnTransformArgs) => Promisable<OnTransformResult>
): 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

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions