Modify Source Webpack Plugin

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

Webpack plugin that allows modification of module source code during compilation via hook functions. Current version 4.1.0 works with Webpack 4 and 5. It uses webpack loader mechanism internally to transform sources, supporting watch mode re-compilation. Key differentiators: cleaner API compared to using raw loaders for conditional modifications; provides access to module path and source; handles loader option serialization issues internally. Release cadence is ad-hoc with breaking changes between major versions (rejection of global variable in v4). Ships TypeScript definitions.

error Module not found: Error: Can't resolve 'modify-source-webpack-plugin'
cause Package not installed or missing from dependencies.
fix
Run npm install --save-dev modify-source-webpack-plugin
error TypeError: ModifySourcePlugin is not a constructor
cause Spawned from incorrect import; e.g., using named import with Node require.
fix
Use const ModifySourcePlugin = require('modify-source-webpack-plugin') or default import.
error Error: ModifySourcePlugin: rules is not iterable
cause Rules option missing or not an array.
fix
Ensure rules is an array of rule objects, e.g., rules: [].
error Cannot read property 'replace' of undefined
cause Modify function returns undefined instead of a string.
fix
Always return the modified source string from the modify function.
breaking v4 replaces global variable approach with direct function passing via loader options. Custom loader rules referencing global variable will break.
fix Update to v4 API: pass functions in rule.modify instead of using global variable.
breaking v3 changes the path argument from filename (e.g., 'index.js') to full path (e.g., '/src/index.js').
fix Update modify functions to handle full file paths instead of just filenames.
deprecated Namespace property in rules is deprecated since v4; use modify directly instead.
fix Replace namespace: { modify: fn } with modify: fn in rule options.
gotcha Loader options may be rehydrated by webpack; do not rely on object references in options.
fix Use simple values or serialize complex data; the plugin handles internal passing.
gotcha TypeScript types may not cover all edge cases; check actual API in source or GitHub issues.
fix Consult the plugin's source code or typings file for undocumented options.
npm install modify-source-webpack-plugin
yarn add modify-source-webpack-plugin
pnpm add modify-source-webpack-plugin

Replaces all occurrences of 'foo' with 'bar' in .js files during webpack compilation.

// webpack.config.js
const ModifySourcePlugin = require('modify-source-webpack-plugin');

module.exports = {
  plugins: [
    new ModifySourcePlugin({
      rules: [
        {
          test: /\.js$/,
          modify: (source, path) => source.replace('foo', 'bar'),
        },
      ],
    }),
  ],
};