esbuild-plugin-transform-ext

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

An esbuild plugin that transforms file extensions in bundled output, addressing esbuild's limitation of not being able to change extensions in the middle of the build process. Version 0.2.5 (current stable) is released under the MIT license. It allows defining per-pattern rules to map output extensions (e.g., .js to .cjs or .mjs) after esbuild's standard out-extension resolution, useful for dual CJS/ESM packages or mixed-format outputs. The plugin is lightweight, TypeScript-first with bundled types, and requires esbuild >=0.19.0 as a peer dependency. Compared to manual post-processing scripts, it integrates directly into esbuild's plugin pipeline without separate tooling.

error Error: Plugin 'transform-ext' returned an error: Cannot read properties of undefined (reading 'replace')
cause Missing or invalid 'map' option in rule; the plugin tries to replace using undefined map.
fix
Ensure each rule has a 'map' object with at least one key (e.g., { '.js': '.mjs' }).
error TypeError: (0 , plugin_transform_ext.transformExtPlugin) is not a function
cause Using CommonJS require() on an ESM-only package.
fix
Use import { transformExtPlugin } from 'esbuild-plugin-transform-ext' or dynamic import().
error Error: Plugin 'transform-ext' returned an error: Pattern must be a RegExp
cause Passing a string instead of RegExp for the 'pattern' option.
fix
Use a RegExp literal: pattern: /\.cjs$/, not pattern: '.cjs$'.
deprecated The 'cwd' option may be removed in future versions in favor of 'absWorkingDir' from esbuild options.
fix If using esbuild >=0.19.0, set absWorkingDir in build options instead of cwd in plugin options.
gotcha Patterns are applied to output file paths, not input paths; ensure pattern matches the final path after outdir and outExtension processing.
fix Test your regex against the output path (e.g., /dist/sub/file.js) not the source path.
gotcha The 'map' option defaults to build.initialOptions.outExtension; if outExtension is not set, no transformation occurs.
fix Always set outExtension in esbuild build options to ensure default mappings are correct.
npm install esbuild-plugin-transform-ext
yarn add esbuild-plugin-transform-ext
pnpm add esbuild-plugin-transform-ext

Shows basic usage of transformExtPlugin with a rule to rename .js to .mjs for .mjs output files.

import { build } from 'esbuild';
import { transformExtPlugin } from 'esbuild-plugin-transform-ext';

const plugin = transformExtPlugin({
  cwd: process.cwd(),
  rules: [
    {
      pattern: /\.mjs$/,
      map: {
        '.js': '.mjs',
      },
    },
  ],
});

await build({
  entryPoints: ['src/index.ts'],
  outdir: 'dist',
  plugins: [plugin],
  outExtension: { '.js': '.mjs' },
  format: 'esm',
});