Webpack String Replacer

raw JSON →
0.0.20 verified Sat Apr 25 auth: no javascript

Webpack plugin to replace strings in modules at configurable build stages. Version 0.0.20 supports three apply stages (loader, optimizeModules, optimizeChunkAssets) and match-count requirements with min/max constraints. Provides TypeScript types, inherited rule/replacement defaults, and validation logging. Differentiates from simple find-and-replace by allowing stage-specific application and output-file-based filtering.

error TypeError: WebpackStringReplacer is not a constructor
cause Using import statement with ES modules in a CommonJS project.
fix
Replace import WebpackStringReplacer from 'webpack-string-replacer' with const WebpackStringReplacer = require('webpack-string-replacer').
error ValidationError: Match count for pattern 'MY_API_TOKEN' not met (min: 4, actual: 0)
cause patternMatchCount.min is set but the pattern never appears in the file.
fix
Verify the pattern exists in the file or reduce/remove the min requirement.
error Error: Plugin cannot use fileInclude and outputFileInclude simultaneously
cause Mixing stage-specific options incorrectly.
fix
Choose one stage and use the corresponding include/exclude options.
error Module not found: Error: Can't resolve 'webpack-string-replacer'
cause Package not installed or not in node_modules.
fix
Run npm install --save-dev webpack-string-replacer from project root.
gotcha When using applyStage: 'loader' or 'optimizeModules', do not use outputFileInclude/outputFileExclude; they are only for 'optimizeChunkAssets'.
fix Use fileInclude/fileExclude for source stages, outputFileInclude/outputFileExclude for chunk stage.
gotcha When using applyStage: 'optimizeChunkAssets', do not use fileInclude/fileExclude; they are only for source stages.
fix Use outputFileInclude/outputFileExclude instead.
gotcha The plugin does not have a default export; using import syntax may fail.
fix Use require('webpack-string-replacer') or TypeScript import with '= require'.
gotcha Pattern with regex flags (e.g., /g) is supported but may not behave as expected if not global.
fix Ensure pattern flags match intended behavior; test with a simple string first.
npm install webpack-string-replacer
yarn add webpack-string-replacer
pnpm add webpack-string-replacer

Shows basic usage: require the plugin, add to webpack plugins with a rule to replace a token in a specific file.

const WebpackStringReplacer = require('webpack-string-replacer');

// webpack config
module.exports = {
  plugins: [
    new WebpackStringReplacer({
      rules: [{
        fileInclude: 'targetFile.js',
        replacements: [{
          pattern: 'MY_API_TOKEN',
          patternMatchCount: { min: 4 },
          replacement: 'lPP5BxQESO6VU4aUcKJLFg',
        }],
      }],
    }),
  ],
};