esbuild-plugin-transform-hook

raw JSON →
0.2.3 verified Fri May 01 auth: no javascript

Esbuild plugin (v0.2.3, 2024) that allows applying custom transformation hooks to build outputs or dependencies, not just sources. Solves gaps in esbuild's native support for polyfill injection, dynamic banners, and importable helpers. Compared to alternatives (e.g., onEnd hooks or manual post-processing), it provides a declarative hook-based API with pattern matching and rename support. Requires esbuild >=0.19.0. Ships TypeScript types. Note: still in PoC status; API may change.

error Error: Cannot find module 'esbuild-plugin-transform-hook'
cause Package not installed or used with require() in an ESM-only environment.
fix
Install with npm install esbuild-plugin-transform-hook and use import instead of require.
error TypeError: transformHookPlugin is not a function
cause Importing the wrong export (e.g., default vs named) or using a bundler that doesn't support ESM.
fix
Use import { transformHookPlugin } from 'esbuild-plugin-transform-hook' and ensure your project is configured for ESM.
error error: [plugin] Error: esbuild version must be >=0.19.0
cause Installed esbuild version is too old (<0.19.0).
fix
Run npm install esbuild@latest to upgrade esbuild to >=0.19.0.
gotcha The plugin is marked as PoC (Proof of Concept). API may change in future versions without major semver bump.
fix Pin to exact version in package.json and test upgrades carefully.
breaking Requires esbuild >=0.19.0. Older esbuild versions (pre-0.19) are not supported and will cause runtime errors.
fix Upgrade esbuild to >=0.19.0.
deprecated The 'on' property currently only accepts 'load' or 'end'. Other values may be silently ignored or cause errors in future versions.
fix Stick to 'load' or 'end' until documentation states otherwise.
npm install esbuild-plugin-transform-hook
yarn add esbuild-plugin-transform-hook
pnpm add esbuild-plugin-transform-hook

Shows how to use the plugin to replace console.log with console.error in TypeScript files during the load phase.

import { build } from 'esbuild'
import { transformHookPlugin } from 'esbuild-plugin-transform-hook'

const plugin = transformHookPlugin({
  hooks: [
    {
      on: 'load',
      pattern: /\.ts$/,
      transform: (source) => {
        return source.replace(/console\.log/g, 'console.error')
      },
      rename: (path) => {
        return path.replace(/\.ts$/, '.js')
      }
    }
  ],
  pattern: /^(?!.*\.html$)/,
})

await build({
  entryPoints: ['index.ts'],
  outdir: 'dist',
  plugins: [plugin],
  format: 'esm',
})
console.log('Build complete')