content-replace-webpack-plugin

raw JSON →
1.0.0 verified Sat Apr 25 auth: no javascript maintenance

A Webpack plugin that replaces asset content during the emit phase. Version 1.0.0 (stable, no recent updates). It allows specifying replacement rules per file extension, and can also operate on external files not in the Webpack asset pipeline. Simpler alternative to string-replace-loader or replace-in-file-webpack-plugin, but lacks advanced features like regex or pattern matching. Limited to function-based replacements and chunk filtering.

error Cannot read property 'source' of undefined
cause Attempting to replace content on a non-existent chunk or external file.
fix
Check that the chunk name in 'chunks' matches an actual entry/async chunk, and that external files exist.
gotcha Replace function must return a string; returning undefined will produce invalid content.
fix Ensure the function returns the modified content string.
gotcha Plugin only operates on emitted assets and external files list. Dynamic imports or code-splitted chunks not in 'chunks' array are ignored.
fix List all chunk names explicitly in the 'chunks' option, or omit to process all chunks.
npm install content-replace-webpack-plugin
yarn add content-replace-webpack-plugin
pnpm add content-replace-webpack-plugin

Shows basic usage: replace 'foo' with 'bar' in JS files and 'old-color' with 'new-color' in CSS files of the 'main' chunk.

// webpack.config.js
const ContentReplacePlugin = require('content-replace-webpack-plugin');
module.exports = {
  entry: './index.js',
  output: { path: './dist', filename: 'bundle.js' },
  plugins: [
    new ContentReplacePlugin({
      chunks: ['main'],
      rules: {
        '.js': content => content.replace('foo', 'bar'),
        '.css': content => content.replace('old-color', 'new-color')
      }
    })
  ]
};