Esbuild plugin to apply custom transformation hooks
PoC
Esbuild and its plugins mostly focus on sources processing, but sometimes additional modifications is also necessary for dependencies or bundles:
- Polyfill injects: esbuild#2840, esbuild#3517, esbuild#3099
- Custom patches: esbuild#3360
- Dynamic banners: esbuild#3291
- Importable helpers: esbuild#1230, esbuild-plugin-extract-helpers
These features will be provided sooner or later, but for now we need a workaround to apply custom transforms.
import { build, BuildOptions } from 'esbuild'
import { transformHookPlugin } from 'esbuild-plugin-transform-hook'
const plugin = transformHookPlugin({
hooks: [
{
on: 'load', // or 'end'
pattern: /\.ts$/,
transform: (source) => {
return source.replace(/console\.log/g, 'console.error')
},
rename: (path) => {
return path.replace(/\.ts$/, '.js')
}
}
],
// optional first-level pattern, defaults to /.$/
pattern: /^(?!.*\.html$)/,
})
const config: BuildOptions = {
entryPoints: ['index.ts'],
outdir: 'target/cjs',
plugins: [plugin],
format: 'cjs',
}
await build(config)