6.0.1 ā€¢ Published 1 month ago

@rollup/plugin-replace v6.0.1

Weekly downloads
1,332,189
License
MIT
Repository
github
Last release
1 month ago

npm size libera manifesto

@rollup/plugin-replace

šŸ£ A Rollup plugin which replaces targeted strings in files while bundling.

Requirements

This plugin requires an LTS Node version (v14.0.0+) and Rollup v1.20.0+.

Install

Using npm:

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

Usage

Create a rollup.config.js configuration file and import the plugin:

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 or the 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] Default: ['\\b', '\\b(?!\\.)']

Specifies the boundaries around which strings will be replaced. By default, delimiters are word boundaries and also prevent replacements of instances with nested access. See 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 (?!\.) boundary
  • typeof windowSmth will not be replaced due to a \b boundary

Delimiters will be used to build a Regexp. To match special characters (any of .*+?^${}()|[]\), be sure to escape them.

objectGuards

Type: Boolean 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:

replace({
  values: {
    'process.env.NODE_ENV': '"production"'
  }
});
// 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 Default: false

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

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

Observe the following code:

// 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] Default: null

A picomatch pattern, 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] Default: null

A picomatch pattern, 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 Default: false

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

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:

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

Can be replaced with:

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

Word Boundaries

By default, values will only match if they are surrounded by word boundaries.

Consider the following options and build file:

module.exports = {
  ...
  plugins: [replace({ changed: 'replaced' })]
};
// file.js
console.log('changed');
console.log('unchanged');

The result would be:

// 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:

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

Meta

CONTRIBUTING

LICENSE (MIT)

workbox-buildvite_wipe_console@lceihen/lc-big-react@giveerr/rollpkg@uponco/admin@g7fe/g7-scripts@vdjurdjevic/generator-react-libadmin-bro-for-nextnode-lib-dependenciesbappo-scriptsschocky@vdjurdjevic/create-react-libdiode-inspr-testdiode-testttdiode-inspr-test-test-testdiode-inspr-testtdiode-testdiode-test-test-diodeinspr-test-diode-testdiode-test-insprinspr-diode-testlegal-content-front-web@nuxt/deployhy-trace-sdkgsmlg-scripts@packmate/uicmtter-lib2@yujinpan/vue-component-packbnc-gulp-multiple-pages@accurate-util/filter-utils40-scripts@workrails/wr-catalog-base@inspr/diode@onereach/step-inputs-common@pega/custom-componenttooltipme-test2mk-beter-cli@svazzle/configcomponent-library-version-betacomponent-library-version-beta-01liger-sdktakla-builderpasscode.jscal-scriptsgreencheap-uikit@elastosfoundation/elastos-hive-js-sdk@adlib/libjcinvccrxfunc@dchagastelles/elastos-hive-js-sdk@danifoldi/nitropack@conorepo/rollup-preset-default@surmon-china/abc-factorysapper-bundler@haseebanwar/react-package-scripts@raysphase/wizard@service-exchange/build@chn-js/canvas-toolsyfrshapeshift-commonshapeshift-identity@skulpture/serve@infinitebrahmanuniverse/nolb-_rolhdlocalhd-sfc-clicreate-oerlikon-appexport-ts@muons/library@paescuj/unbuildcrmnext-uxmui-react-chatexammppleeqfvitemuteswanlc-big-reactwitosveltenetnstbrowser-node-sdksssiiixxxvuesfcbuilderzhenyu-componentszhenyu-z-components@everything-registry/sub-chunk-788@senzo/core@leijingdao/tsdx@typhonjs-node-rollup/plugin-replaceyakshaving@ukpc/exposemedusa-admin-fa@perseides/admin@surmon/libundlerevolve-tests@xenon.js/rollup-plugin-misckayser-buildtal-fragment-element-uitarattaro2reacttenflyer-pluginsvelte-simple-progressbarsvelte-dashboard-starter
6.0.1

1 month ago

6.0.0

1 month ago

5.0.6

5 months ago

5.0.7

5 months ago

5.0.5

1 year ago

5.0.4

1 year ago

5.0.3

1 year ago

5.0.2

2 years ago

5.0.1

2 years ago

5.0.0

2 years ago

3.1.0

3 years ago

4.0.0

3 years ago

3.0.1

3 years ago

3.0.0

3 years ago

2.4.2

4 years ago

2.4.1

4 years ago

2.4.0

4 years ago

2.3.4

4 years ago

2.3.3

4 years ago

2.3.2

5 years ago

2.3.1

5 years ago

2.3.0

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago