UNPKG

6.14 kBMarkdownView Raw
1[npm]: https://img.shields.io/npm/v/@rollup/plugin-replace
2[npm-url]: https://www.npmjs.com/package/@rollup/plugin-replace
3[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-replace
4[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-replace
5
6[![npm][npm]][npm-url]
7[![size][size]][size-url]
8[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
9
10# @rollup/plugin-replace
11
12🍣 A Rollup plugin which replaces targeted strings in files while bundling.
13
14## Requirements
15
16This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
17
18## Install
19
20Using npm:
21
22```console
23npm install @rollup/plugin-replace --save-dev
24```
25
26## Usage
27
28Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
29
30```js
31import replace from '@rollup/plugin-replace';
32
33export default {
34 input: 'src/index.js',
35 output: {
36 dir: 'output',
37 format: 'cjs'
38 },
39 plugins: [
40 replace({
41 'process.env.NODE_ENV': JSON.stringify('production'),
42 __buildDate__: () => JSON.stringify(new Date()),
43 __buildVersion: 15
44 })
45 ]
46};
47```
48
49Then 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).
50
51The 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.
52
53_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._
54
55Typically, `@rollup/plugin-replace` should be placed in `plugins` _before_ other plugins so that they may apply optimizations, such as dead code removal.
56
57## Options
58
59In addition to the properties and values specified for replacement, users may also specify the options below.
60
61### `delimiters`
62
63Type: `Array[String, String]`<br>
64Default: `['\\b', '\\b(?!\\.)']`
65
66Specifies the boundaries around which strings will be replaced. By default, delimiters are [word boundaries](https://www.regular-expressions.info/wordboundaries.html) and also prevent replacements of instances with nested access. See [Word Boundaries](#word-boundaries) below for more information.
67For example, if you pass `typeof window` in `values` to-be-replaced, then you could expect the following scenarios:
68
69- `typeof window` **will** be replaced
70- `typeof window.document` **will not** be replaced due to `(?!\.)` boundary
71- `typeof windowSmth` **will not** be replaced due to a `\b` boundary
72
73Delimiters 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.
74
75### `objectGuards`
76
77Type: `Boolean`<br>
78Default: `false`
79
80When replacing dot-separated object properties like `process.env.NODE_ENV`, will also replace `typeof process` object guard
81checks against the objects with the string `"object"`.
82
83For example:
84
85```js
86replace({
87 values: {
88 'process.env.NODE_ENV': '"production"'
89 }
90});
91```
92
93```js
94// Input
95if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') {
96 console.log('production');
97}
98// Without `objectGuards`
99if (typeof process !== 'undefined' && 'production' === 'production') {
100 console.log('production');
101}
102// With `objectGuards`
103if ('object' !== 'undefined' && 'production' === 'production') {
104 console.log('production');
105}
106```
107
108### `preventAssignment`
109
110Type: `Boolean`<br>
111Default: `false`
112
113Prevents replacing strings where they are followed by a single equals sign. For example, where the plugin is called as follows:
114
115```js
116replace({
117 values: {
118 'process.env.DEBUG': 'false'
119 }
120});
121```
122
123Observe the following code:
124
125```js
126// Input
127process.env.DEBUG = false;
128if (process.env.DEBUG == true) {
129 //
130}
131// Without `preventAssignment`
132false = false; // this throws an error because false cannot be assigned to
133if (false == true) {
134 //
135}
136// With `preventAssignment`
137process.env.DEBUG = false;
138if (false == true) {
139 //
140}
141```
142
143### `exclude`
144
145Type: `String` | `Array[...String]`<br>
146Default: `null`
147
148A [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.
149
150### `include`
151
152Type: `String` | `Array[...String]`<br>
153Default: `null`
154
155A [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.
156
157### `values`
158
159Type: `{ [key: String]: Replacement }`, where `Replacement` is either a string or a `function` that returns a string.
160Default: `{}`
161
162To avoid mixing replacement strings with the other options, you can specify replacements in the `values` option. For example, the following signature:
163
164```js
165replace({
166 include: ['src/**/*.js'],
167 changed: 'replaced'
168});
169```
170
171Can be replaced with:
172
173```js
174replace({
175 include: ['src/**/*.js'],
176 values: {
177 changed: 'replaced'
178 }
179});
180```
181
182## Word Boundaries
183
184By default, values will only match if they are surrounded by _word boundaries_.
185
186Consider the following options and build file:
187
188```js
189module.exports = {
190 ...
191 plugins: [replace({ changed: 'replaced' })]
192};
193```
194
195```js
196// file.js
197console.log('changed');
198console.log('unchanged');
199```
200
201The result would be:
202
203```js
204// file.js
205console.log('replaced');
206console.log('unchanged');
207```
208
209To ignore word boundaries and replace every instance of the string, wherever it may be, specify empty strings as delimiters:
210
211```js
212export default {
213 ...
214 plugins: [
215 replace({
216 changed: 'replaced',
217 delimiters: ['', '']
218 })
219 ]
220};
221```
222
223## Meta
224
225[CONTRIBUTING](/.github/CONTRIBUTING.md)
226
227[LICENSE (MIT)](/LICENSE)