0
# @rollup/plugin-replace
1
2
A Rollup plugin that replaces targeted strings in files during the bundling process. It provides comprehensive configuration options for precise string replacement, including customizable delimiters, word boundary matching, object guard replacement, and assignment prevention to enable build-time code transformations, environment variable injection, and preprocessing workflows.
3
4
## Package Information
5
6
- **Package Name**: @rollup/plugin-replace
7
- **Package Type**: npm
8
- **Language**: TypeScript/JavaScript
9
- **Installation**: `npm install @rollup/plugin-replace --save-dev`
10
11
## Core Imports
12
13
```typescript
14
import replace from '@rollup/plugin-replace';
15
```
16
17
For CommonJS:
18
19
```javascript
20
const replace = require('@rollup/plugin-replace');
21
```
22
23
## Basic Usage
24
25
```typescript
26
import replace from '@rollup/plugin-replace';
27
28
export default {
29
input: 'src/index.js',
30
output: {
31
dir: 'output',
32
format: 'cjs'
33
},
34
plugins: [
35
replace({
36
'process.env.NODE_ENV': JSON.stringify('production'),
37
__buildDate__: () => JSON.stringify(new Date()),
38
__buildVersion: 15
39
})
40
]
41
};
42
```
43
44
## Capabilities
45
46
### Replace Plugin Function
47
48
Creates a Rollup plugin instance for string replacement during bundling.
49
50
```typescript { .api }
51
/**
52
* Creates a Rollup plugin for string replacement during bundling
53
* @param options - Configuration options for replacement patterns and behavior
54
* @returns Rollup Plugin object with transform and renderChunk hooks
55
*/
56
function replace(options?: RollupReplaceOptions): Plugin;
57
58
interface RollupReplaceOptions {
59
/**
60
* All other options are treated as string: replacement replacers,
61
* or string: (id) => replacement functions.
62
*/
63
[str: string]:
64
| Replacement
65
| RollupReplaceOptions['include']
66
| RollupReplaceOptions['values']
67
| RollupReplaceOptions['objectGuards']
68
| RollupReplaceOptions['preventAssignment']
69
| RollupReplaceOptions['sourceMap']
70
| RollupReplaceOptions['sourcemap'];
71
72
/**
73
* A picomatch pattern, or array of patterns, of files that should be
74
* processed by this plugin (if omitted, all files are included by default)
75
*/
76
include?: FilterPattern;
77
78
/**
79
* Files that should be excluded, if include is otherwise too permissive.
80
*/
81
exclude?: FilterPattern;
82
83
/**
84
* If false, skips source map generation. This will improve performance.
85
* @default true
86
*/
87
sourceMap?: boolean;
88
89
/**
90
* If false, skips source map generation. This will improve performance.
91
* Alternative lowercase spelling of sourceMap.
92
* @default true
93
*/
94
sourcemap?: boolean;
95
96
/**
97
* To replace every occurrence of <@foo@> instead of every occurrence
98
* of foo, supply delimiters
99
* @default ['\\b', '\\b(?!\\.)']
100
*/
101
delimiters?: [string, string];
102
103
/**
104
* When replacing dot-separated object properties like process.env.NODE_ENV,
105
* will also replace typeof process object guard checks against the objects
106
* with the string "object".
107
* @default false
108
*/
109
objectGuards?: boolean;
110
111
/**
112
* Prevents replacing strings where they are followed by a single equals
113
* sign.
114
* @default false
115
*/
116
preventAssignment?: boolean;
117
118
/**
119
* You can separate values to replace from other options.
120
*/
121
values?: { [str: string]: Replacement };
122
}
123
124
type Replacement = string | ((id: string) => string);
125
126
type FilterPattern = string | RegExp | (string | RegExp)[];
127
128
interface Plugin {
129
name: string;
130
buildStart(): void;
131
transform(code: string, id: string): TransformResult | null;
132
renderChunk(code: string, chunk: ChunkInfo): TransformResult | null;
133
}
134
135
interface TransformResult {
136
code: string;
137
map?: SourceMap;
138
}
139
140
interface ChunkInfo {
141
fileName: string;
142
// ... other chunk properties
143
}
144
145
interface SourceMap {
146
// Standard source map object
147
// Details depend on source-map library implementation
148
}
149
```
150
151
**Usage Examples:**
152
153
```typescript
154
// Simple string replacement
155
replace({
156
'process.env.NODE_ENV': JSON.stringify('production'),
157
__VERSION__: JSON.stringify(process.env.npm_package_version)
158
})
159
160
// Function-based replacement
161
replace({
162
__buildDate__: () => JSON.stringify(new Date()),
163
__buildUser__: (id) => JSON.stringify(process.env.USER)
164
})
165
166
// Using values object to separate replacements
167
replace({
168
include: ['src/**/*.js'],
169
exclude: ['src/vendor/**'],
170
values: {
171
'DEBUG': 'false',
172
'API_URL': JSON.stringify('https://api.prod.example.com')
173
}
174
})
175
176
// Custom delimiters for precise matching
177
replace({
178
delimiters: ['<@', '@>'],
179
'<@VERSION@>': '1.0.0',
180
'<@BUILD_ID@>': process.env.BUILD_ID
181
})
182
183
// Object guards for typeof checks
184
replace({
185
objectGuards: true,
186
'process.env.NODE_ENV': '"production"'
187
})
188
// Transforms: typeof process !== 'undefined' && process.env.NODE_ENV === 'production'
189
// Into: 'object' !== 'undefined' && 'production' === 'production'
190
191
// Prevent assignment replacement
192
replace({
193
preventAssignment: true,
194
'process.env.DEBUG': 'false'
195
})
196
// Leaves: process.env.DEBUG = false (assignment)
197
// Replaces: if (process.env.DEBUG === true) (comparison)
198
199
// File filtering
200
replace({
201
include: ['src/**/*.{js,ts}', 'lib/**/*.js'],
202
exclude: ['**/*.test.*', 'src/legacy/**'],
203
'OLD_API': 'NEW_API'
204
})
205
206
// Source map control
207
replace({
208
sourceMap: false, // Disable for better performance
209
'DEBUG_MODE': 'false'
210
})
211
212
// Alternative sourcemap spelling
213
replace({
214
sourcemap: process.env.NODE_ENV === 'development', // Enable in dev only
215
'FEATURE_FLAG': 'true'
216
})
217
```
218
219
**Advanced Configuration:**
220
221
```typescript
222
// Complex replacement with multiple patterns
223
replace({
224
// File filtering
225
include: ['src/**/*.{js,ts,jsx,tsx}'],
226
exclude: ['**/*.test.*', '**/*.spec.*'],
227
228
// Replacement options
229
preventAssignment: true,
230
objectGuards: true,
231
delimiters: ['\\b', '\\b(?!\\.)'],
232
233
// Environment-based replacements
234
values: {
235
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
236
'process.env.API_URL': JSON.stringify(process.env.API_URL),
237
'__VERSION__': JSON.stringify(require('./package.json').version),
238
'__BUILD_TIME__': () => JSON.stringify(new Date().toISOString()),
239
'__GIT_HASH__': () => {
240
try {
241
return JSON.stringify(require('child_process')
242
.execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim());
243
} catch {
244
return '"unknown"';
245
}
246
}
247
},
248
249
// Source maps for debugging (sourceMap or sourcemap both work)
250
sourceMap: process.env.NODE_ENV === 'development'
251
})
252
```
253
254
## Error Handling
255
256
The plugin will emit warnings in the following cases:
257
258
- When `preventAssignment` is not explicitly set to `true` or `false`, a deprecation warning is shown during `buildStart`
259
- If replacement patterns don't match any content, no errors are thrown
260
- Invalid regex patterns in `delimiters` will cause runtime errors during plugin initialization
261
262
Common issues and solutions:
263
264
```typescript
265
// Problem: Replacement not working due to word boundaries
266
replace({ 'API': 'newAPI' }) // Won't replace 'myAPI'
267
268
// Solution: Use empty delimiters or adjust pattern
269
replace({
270
delimiters: ['', ''],
271
'API': 'newAPI'
272
}) // Will replace 'myAPI' -> 'mynewAPI'
273
274
// Problem: Accidental assignment replacement
275
replace({ 'DEBUG': 'false' }) // Converts 'DEBUG = true' to 'false = true' (error)
276
277
// Solution: Enable preventAssignment
278
replace({
279
preventAssignment: true,
280
'DEBUG': 'false'
281
}) // Leaves assignments alone
282
```
283
284
## Integration Notes
285
286
- **Plugin Order**: Place `@rollup/plugin-replace` before other plugins so they can apply optimizations like dead code removal
287
- **Performance**: Disable source maps in production builds for better performance
288
- **Node.js Requirements**: Requires Node.js v14.0.0+ and Rollup v1.20.0+
289
- **Peer Dependencies**: Rollup is a peer dependency (v1.20.0 || v2.x || v3.x || v4.x)