npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

rollup-plugin-replace-regex

v1.1.0

Published

Replace regex strings in files while bundling

Downloads

13

Readme

rollup-plugin-replace-regex

This is a modified copy of @rollup/plugin-replace with the ability to match regular expression strings and process conditional comment blocks.

Changes and additions to RollupReplaceOptions

The RollupReplaceOptions type is defined here.

Regex values

New regexValues key to specify replacement pairs where the key can be a regular expression.

  • key may contain regex expression (except regex group definitions)
    • regex keys ignore the boundaries option, but boundaries can be added as part of the regex manually
  • value is a string or function that gets
    • file id
    • matched expression by regex key
    • original matched regex key from regexValues

Conditional comments

  • comments

    Special source code comment marks are converted to: | source | result | | --- |--- | | /{}/ | // | | /[condition]{}/ | //[condition]{}/| | /[condition]{/ | /[condition]{/ and line comments | |until the next closing mark| | /[condition]}/ | /[condition]}/| | /[condition]}/ | /[condition]}*/|

    It is possible to specify multiple conditions in a single line and the line won't be commneted only if all of them are defined:

    /* [aa]<> */ // This line adds 'aa' to allowed definitions
    /* [bb]<> */ // This line adds 'bb' to allowed definitions
    /*[aa]{}*/ /*[bb]{}*/ 'aa and bb are defined' 

    If commentsForRelease option is true then all conditional blocks will be commented regardless defined conditions

  • conditions

    • additional conditions for comments
  • commentsForRelease

  • verbose

    • print matching and comments process results.

Execution order

rollup-plugin-replace-regex supports three diffent modes:

  • values replace
  • values with regular expressions
  • comments

comments operation is executed before values replace. If you need opposite then call rollup-plugin-replace-regex plugin twice:

  plugins: [
      rollup-plugin-replace-regex({values: ...}),
      rollup-plugin-replace-regex({cooments: true}),
  ]

TODO

Add an option to specify when to run actions. Now we run all jobs on transform hook vs. orignal plugin does both transform and renderChunk hooks.

@rollup/plugin-replace

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

npm size libera manifesto

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.

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)