# @rollup/plugin-replace

> Replace strings in files while bundling

Latest version **6.0.3** (published 2025-10-29) · MIT license · 0 weekly downloads

## Install

```sh
npm install @rollup/plugin-replace
pnpm add @rollup/plugin-replace
yarn add @rollup/plugin-replace
bun add @rollup/plugin-replace
```

## Health

**Score 60/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 6.0.3 |
| Published | 2025-10-29 |
| First published | 2019-10-28 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=14.0.0 |
| Dependencies | 2 |
| Unpacked size | 23.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 3757 |
| Author | Rich Harris |
| Maintainers | shellscape, rich_harris, guybedford, lukastaegert |
| Keywords | rollup, plugin, replace, es2015, npm, modules |

## Links

- npm: https://www.npmjs.com/package/@rollup/plugin-replace
- Repository: https://github.com/rollup/plugins
- Homepage: https://github.com/rollup/plugins/tree/master/packages/replace#readme
- Issues: https://github.com/rollup/plugins/issues
- npm.io page: https://npm.io/package/@rollup/plugin-replace

## Dependencies (2)

- [magic-string](https://npm.io/package/magic-string.md) ^0.30.3
- [@rollup/pluginutils](https://npm.io/package/@rollup/pluginutils.md) ^5.0.1

## Alternatives

- [raw-loader](https://npm.io/package/raw-loader.md) — 4.3M weekly downloads
- [plop](https://npm.io/package/plop.md) — 1.4M weekly downloads
- [webpack-deadcode-plugin](https://npm.io/package/webpack-deadcode-plugin.md) — 80.3K weekly downloads
- [@storybook/preact-vite](https://npm.io/package/@storybook/preact-vite.md) — 54.2K weekly downloads
- [vite-plugin-transform](https://npm.io/package/vite-plugin-transform.md) — 2.4K weekly downloads

## Recent versions

- 6.0.3 (latest) — 2025-10-29
- 6.0.2 — 2024-12-15
- 6.0.1 — 2024-09-23
- 6.0.0 — 2024-09-23
- 5.0.7 — 2024-06-05
- 5.0.6 — 2024-06-05
- 5.0.5 — 2023-10-29
- 5.0.4 — 2023-10-15
- 5.0.3 — 2023-10-05
- 5.0.2 — 2022-12-17
- 5.0.1 — 2022-10-21
- 5.0.0 — 2022-10-10
- 4.0.0 — 2022-02-22
- 3.1.0 — 2022-02-11
- 3.0.1 — 2021-12-28
- … 11 more at https://npm.io/package/@rollup/plugin-replace/versions

## README

[npm]: https://img.shields.io/npm/v/@rollup/plugin-replace
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-replace
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-replace
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-replace

[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)

# @rollup/plugin-replace

🍣 A Rollup plugin which replaces targeted strings in files while bundling.

## Requirements

This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.

## Install

Using npm:

```console
npm install @rollup/plugin-replace --save-dev
```

## Usage

Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:

```js
import replace from '@rollup/plugin-replace';

export default {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [
    replace({
      'process.env.NODE_ENV': JSON.stringify('production'),
      __buildDate__: () => JSON.stringify(new Date()),
      __buildVersion: 15
    })
  ]
};
```

Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).

The configuration above will replace every instance of `process.env.NODE_ENV` with `"production"` and `__buildDate__` with the result of the given function in any file included in the build.

_Note: Values must be either primitives (e.g. string, number) or `function` that returns a string. For complex values, use `JSON.stringify`. To replace a target with a value that will be evaluated as a string, set the value to a quoted string (e.g. `"test"`) or use `JSON.stringify` to preprocess the target string safely._

Typically, `@rollup/plugin-replace` should be placed in `plugins` _before_ other plugins so that they may apply optimizations, such as dead code removal.

## Options

In addition to the properties and values specified for replacement, users may also specify the options below.

### `delimiters`

Type: `Array[String, String]`<br>
Default: `['(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])', '(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)']`

Specifies the boundaries around which strings will be replaced. By default, delimiters match JavaScript identifier boundaries and also prevent replacements of instances with nested access. See [Word Boundaries](#word-boundaries) below for more information.
For example, if you pass `typeof window` in `values` to-be-replaced, then you could expect the following scenarios:

- `typeof window` **will** be replaced
- `typeof window.document` **will not** be replaced due to the `(?!\.)` boundary
- `typeof windowSmth` **will not** be replaced due to identifier boundaries

Delimiters will be used to build a `Regexp`. To match special characters (any of `.*+?^${}()|[]\`), be sure to [escape](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping) them.

### `objectGuards`

Type: `Boolean`<br>
Default: `false`

When replacing dot-separated object properties like `process.env.NODE_ENV`, will also replace `typeof process` object guard
checks against the objects with the string `"object"`.

For example:

```js
replace({
  values: {
    'process.env.NODE_ENV': '"production"'
  }
});
```

```js
// Input
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') {
  console.log('production');
}
// Without `objectGuards`
if (typeof process !== 'undefined' && 'production' === 'production') {
  console.log('production');
}
// With `objectGuards`
if ('object' !== 'undefined' && 'production' === 'production') {
  console.log('production');
}
```

### `preventAssignment`

Type: `Boolean`<br>
Default: `false`

Prevents replacing strings where they are followed by a single equals sign. For example, where the plugin is called as follows:

```js
replace({
  values: {
    'process.env.DEBUG': 'false'
  }
});
```

Observe the following code:

```js
// Input
process.env.DEBUG = false;
if (process.env.DEBUG == true) {
  //
}
// Without `preventAssignment`
false = false; // this throws an error because false cannot be assigned to
if (false == true) {
  //
}
// With `preventAssignment`
process.env.DEBUG = false;
if (false == true) {
  //
}
```

### `exclude`

Type: `String` | `Array[...String]`<br>
Default: `null`

A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default no files are ignored.

### `include`

Type: `String` | `Array[...String]`<br>
Default: `null`

A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.

### `sourceMap` or `sourcemap`

Type: `Boolean`<br>
Default: `false`

Enables generating sourcemaps for the bundled code. For example, where the plugin is called as follows:

```js
replace({
  sourcemap: true
});
```

### `values`

Type: `{ [key: String]: Replacement }`, where `Replacement` is either a string or a `function` that returns a string.
Default: `{}`

To avoid mixing replacement strings with the other options, you can specify replacements in the `values` option. For example, the following signature:

```js
replace({
  include: ['src/**/*.js'],
  changed: 'replaced'
});
```

Can be replaced with:

```js
replace({
  include: ['src/**/*.js'],
  values: {
    changed: 'replaced'
  }
});
```

## Word Boundaries

By default, values will only match if they are surrounded by _word boundaries_ that respect JavaScript's rules for valid identifiers (including `$` and `_` as valid identifier characters).

Consider the following options and build file:

```js
module.exports = {
  ...
  plugins: [replace({ changed: 'replaced' })]
};
```

```js
// file.js
console.log('changed');
console.log('unchanged');
```

The result would be:

```js
// file.js
console.log('replaced');
console.log('unchanged');
```

To ignore word boundaries and replace every instance of the string, wherever it may be, specify empty strings as delimiters:

```js
export default {
  ...
  plugins: [
    replace({
      changed: 'replaced',
      delimiters: ['', '']
    })
  ]
};
```

## Meta

[CONTRIBUTING](/.github/CONTRIBUTING.md)

[LICENSE (MIT)](/LICENSE)

---
_Source: https://npm.io/package/@rollup/plugin-replace · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
