esbuild-plugin-replace
raw JSON → 1.4.0 verified Fri May 01 auth: no javascript
An esbuild plugin for replacing strings in files during bundling, inspired by @rollup/plugin-replace. Current stable version is 1.4.0. Release cadence appears sporadic with occasional bug fixes and feature additions. Key differentiators: provides include/exclude file filtering, configurable delimiters, and supports both flat replacement objects and a `values` option to separate replacements from plugin options. Delimiters default to word boundaries. Requires Node.js and esbuild. Ships TypeScript declarations.
Common errors
error Error: The replace plugin expects replacement values to be strings or functions, got object ↓
cause Passing an object directly instead of using JSON.stringify
fix
replace({ '__config__': JSON.stringify({ key: 'value' }) })
error TypeError: Cannot read properties of undefined (reading 'replace') ↓
cause Passing a non-string value as replacement (e.g., number) without converting to string
fix
Ensure replacement values are either strings or functions that return strings, e.g., JSON.stringify(123)
Warnings
gotcha Values must be primitives or functions returning a string. Complex values must be JSON.stringify'd. ↓
fix Use JSON.stringify for objects/arrays: replace({ '__key__': JSON.stringify({foo: 'bar'}) })
breaking v1.0.8 introduced a change that may break builds using the `values` option incorrectly. ↓
fix If using `values` with existing flat replace keys, ensure keys are not duplicated between the top-level and values object.
deprecated Specifying replacements as top-level keys alongside plugin options is discouraged in favor of the `values` option. ↓
fix Use the `values` option: replace({ values: { ... } })
Install
npm install esbuild-plugin-replace yarn add esbuild-plugin-replace pnpm add esbuild-plugin-replace Imports
- replace wrong
import replace from 'esbuild-plugin-replace'correctimport { replace } from 'esbuild-plugin-replace'
Quickstart
const esbuild = require('esbuild');
const { replace } = require('esbuild-plugin-replace');
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
plugins: [
replace({
'__version__': JSON.stringify('1.0.0'),
'__author__': JSON.stringify('author'),
}),
],
}).then(() => console.log('Build succeeded')).catch(() => process.exit(1));