esbuild Plugin Replace Regex
raw JSON → 0.0.2 verified Fri May 01 auth: no javascript
A simple esbuild plugin for replacing file content during bundling using regular expressions or string patterns. Version 0.0.2, released with basic functionality allowing multiple patterns, custom file filtering, and loader specification. Differentiates from general replace plugins by focusing on regex and integration with esbuild's build process. Lightweight with no additional dependencies beyond esbuild peer.
Common errors
error TypeError: replacePlugin is not a function ↓
cause Using named import instead of default import in ESM
fix
Import default: import replacePlugin from 'esbuild-plugin-replace-regex'
error Error: The plugin 'replace-regex' returned an error: Cannot read properties of undefined (reading 'replace') ↓
cause Patterns array item is malformed or missing replacement string
fix
Ensure each pattern is either [search, replacement] or [regex, replaceFunction]
Warnings
gotcha Patterns array items can be string pairs or regex with function replacements; using regex without global flag may replace only first occurrence ↓
fix Add g flag to regex or use string replacement for all occurrences
gotcha The filter option is a RegExp that matches the file path; using a string will throw an error ↓
fix Use a RegExp object for filter
Install
npm install esbuild-plugin-replace-regex yarn add esbuild-plugin-replace-regex pnpm add esbuild-plugin-replace-regex Imports
- default wrong
const replacePlugin = require('esbuild-plugin-replace-regex')correctimport replacePlugin from 'esbuild-plugin-replace-regex' - replacePlugin wrong
import { replacePlugin } from 'esbuild-plugin-replace-regex'correctconst replacePlugin = require('esbuild-plugin-replace-regex');
Quickstart
import esbuild from 'esbuild';
import replacePlugin from 'esbuild-plugin-replace-regex';
await esbuild.build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/bundle.js',
plugins: [
replacePlugin({
filter: /\.(ts|js)$/,
patterns: [
['VERSION', '1.0.0'],
[/process\.env\.NODE_ENV/g, '"production"'],
]
})
]
});