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

regex-replace-loader

v1.0.2

Published

A webpack loader to replace values in files using regex

Downloads

116

Readme

regex-replace-loader

Build Status

A webpack loader that uses regex to replace values in files, or transform source into another form.

The regex-replace-loader takes a file's content as input, runs it against a user-supplied regular expression, and makes substitutions based on the user-supplied replace value, which can be either a string or a function that returns a value.

Example usage

Replace a specific string in a file with another.

Input

All must depart the auditorium.
All must exit through the side door.

webpack.config.js

module.exports = {
  ...,
  module: {
    rules: [{
      test: /\.source.txt$/,
      use: {
        loader: 'regex-replace-loader',
        options: {
          regex: 'All',     // can also be a RegExp object (required)
          flags: 'g'        // ignored if a RegExp is used (optional)
          value: 'y\'all',  // the replace value (required, can also be a function)
        }
      }
    }]
  }
}

Output

y'all must depart the auditorium.
y'all must exit through the side door.

Multiple replace stages

The regex-replace-loader supports running multiple replace operations in stages, where the output of each stage is the input source for the next.

Input

Today's date is THE_DATE
The time is THE_TIME

webpack.config.js

module.exports = {
  ...,
  module: {
    rules: [{
      test: /\.source.txt$/,
      use: {
        loader: 'regex-replace-loader',
        options: {
          stages: [{
            regex: 'THE_DATE',
            flags: '',
            value: new Date().toDateString(),
          },
          {
            regex: 'THE_TIME',
            flags: '',
            value: new Date().toTimeString(),
          }]
        }
      }
    }]
  }
}

Output

Today's date is Sat Dec 09 2017
The time is 10:14:52 GMT-0800 (PST)

Typescript

Using import instead of require may cause issues when using Typescript to import text files. In this case, include a declarations.d.ts file in your project:

declarations.d.ts

declare module '*.txt' {
  const txt: any
  export default txt
}

declare module '*.json' {
  const json: any
  export default json
}

declare module '*.whatever' {
  const value: any
  export default value
}

Then you should be able to import the file:

import text from './somefile.txt'
import json from './someinfo.json'

Options object

options: {
  regex: '<search expression>' | /search expression/<flags>,
  flags: 'g', // Ignored if regex is a RegExp object
  value: '<replace value>' | function (match) { return 'some value' },
  stages: [ {options}, {options}, ... ]
}

regex (string|RegExp) (required) can be a string or RegExp object. For strings make sure escape characters use a double backslash, e.g., \\w+.

flags (string) (optional) used if regex is a string, otherwise ignored. If g (global) is specified either in the flags property or in the supplied regex, a replace operations will be performed for each match in the source.

value (string|function) (required) the replace value.

stages (object) (optional) a list of regex, flags and value objects for performing multiple match/replace operations on the same source:

stages: [
  { regex: 'a', flags: 'gi', value: '1' },
  { regex: 'b', flags: 'gi', value: '2' },
  { regex: 'c', flags: 'gi', value: '3' }
]

Using the value option

The options.value parameter can be a string or function. While using a function is more flexible and powerful, there are some special uses when options.value is a string.

value as a string

When options.value is a string, certain special replacement patterns are available.

Pattern | Inserts ------- | ------- $$ | Inserts a "$". $& | Inserts the matched substring. $` | Inserts the portion of the string that precedes the matched substring. $' | Inserts the portion of the string that follows the matched substring. $n | Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed.

Specifying a string as a parameter

For example, $& inserts the matched substring, so setting options.value to $& would result in an "identity" operation.

It may be handy in some cases to use the matched substring as part of the replace value:

Input

All must depart the auditorium.

Options

options: {
  regex: 'All',
  flags: ''
  value: "y'$&",  // output the matched substring as part of the value
}

Outupt

y'All must depart the auditorium.

The $n pattern inserts a match group:

Input

y = 2x + 3

Options

options: {
  regex: /(\w) = (\d+)(\w) \+ (\d+)/,
  // Replace the match with a summary of contents.
  value: 'variables: $1, $3\nconstants: $2, $4',
}

Outupt

variables: y, x
constants: 2, 3

value as a function

When options.value is a function, the replace capabilities become more powerful.

The value function receives a match object with the following elements:

Property/Index | Description -------------- | ----------- [0] | The full string of characters matched [1], ...[n ] | The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited. index | The 0-based index of the match in the string. input | The original string.

The RegExp match object

value: function (match) {
  match[0]        // the full match
  match[1]        // the first capture group
  match[2]        // the second capture group, etc.
  match['index']  // the position of the match in the input string
  match['input']  // the original source input string

  return match[0] // This would result in an "identity" operation,
                  // where the replaced value is the same as the
                  // original matched value
}

Input

Today's date is #{date}
The time is #{time}

Options

options: {
  regex: /#\{(.+?)\}/g,
  // Render variables to a template
  value: function (match) {
    const context = {
      date: new Date().toDateString(),
      time: new Date().toTimeString()
    }
    // If there is no variable, return the original template match.
    return context[match[1]] || match[0]
  }
}

Outupt

  Today's date is Sat Dec 09 2017
  The time is 11:51:25 GMT-0800 (PST)