webpack-inject-plugin
raw JSON → 1.5.5 verified Sat Apr 25 auth: no javascript
A webpack plugin to dynamically inject arbitrary code into the bundle at build time. Current stable version is 1.5.5, compatible with webpack >=4.0.0. It allows injection via a loader function (synchronous or async), with options for entry filtering and ordering (First, Last, NotLast). Unlike other injection plugins, it leverages webpack's loader context and supports multiple plugin instances with unique loader IDs. Useful for polyfills, instrumentation, or config-driven code injection.
Common errors
error TypeError: InjectPlugin is not a constructor ↓
cause CommonJS require does not automatically resolve default export (ESM-style).
fix
Use const InjectPlugin = require('webpack-inject-plugin').default;
error Module not found: Error: Can't resolve 'webpack-inject-plugin' ↓
cause Missing installation or webpack version mismatch (requires webpack >=4.0.0).
fix
Run npm install webpack-inject-plugin --save-dev and ensure webpack is >=4.
error Error: ENTRY_ORDER is not defined ↓
cause Imported incorrectly; ENTRY_ORDER is a named export.
fix
Import with const { ENTRY_ORDER } = require('webpack-inject-plugin');
Warnings
gotcha In CommonJS, the default export is not the plugin constructor; you must use require('webpack-inject-plugin').default. ↓
fix Use const InjectPlugin = require('webpack-inject-plugin').default;
deprecated The entryOrder option defaults to ENTRY_ORDER.NotLast. If you rely on the default, you may get unexpected bundle order. ↓
fix Explicitly set entryOrder to ENTRY_ORDER.First or ENTRY_ORDER.Last if you need exact control.
gotcha The injected code runs in the bundle's module scope, not the global scope unless you explicitly assign to window or global. ↓
fix To inject global code, wrap it in self-executing function or assign to globalThis.
breaking In v1.5.0, the loader ID handling changed. Multiple instances may conflict if IDs are not unique. ↓
fix Provide a unique loaderID option for each InjectPlugin instance if you use more than one.
Install
npm install webpack-inject-plugin yarn add webpack-inject-plugin pnpm add webpack-inject-plugin Imports
- default wrong
const InjectPlugin = require('webpack-inject-plugin')correctimport InjectPlugin from 'webpack-inject-plugin' - ENTRY_ORDER wrong
import ENTRY_ORDER from 'webpack-inject-plugin'correctimport { ENTRY_ORDER } from 'webpack-inject-plugin' - default (CommonJS) wrong
const InjectPlugin = require('webpack-inject-plugin')correctconst InjectPlugin = require('webpack-inject-plugin').default
Quickstart
// webpack.config.js
const InjectPlugin = require('webpack-inject-plugin').default;
module.exports = {
entry: './src/index.js',
output: { filename: 'bundle.js' },
plugins: [
new InjectPlugin(() => {
return "console.log('Injected code!');";
}, {
entryName: 'main',
entryOrder: require('webpack-inject-plugin').ENTRY_ORDER.Last
})
]
};