Rollup plugin that scans modules for global variables and injects import statements where necessary
npx @tessl/cli install tessl/npm-rollup--plugin-inject@5.0.0The @rollup/plugin-inject package is a Rollup plugin that automatically scans JavaScript modules for global variable usage and dynamically injects import statements where necessary. It provides a comprehensive solution for module dependency management by analyzing code for references to global variables (like Promise, $, fs, etc.) and automatically generating the appropriate import statements at build time.
npm install @rollup/plugin-inject --save-devimport inject from '@rollup/plugin-inject';For CommonJS:
const inject = require('@rollup/plugin-inject');import inject from '@rollup/plugin-inject';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [
inject({
// Inject jQuery as $
$: 'jquery',
// Inject named import
Promise: ['es6-promise', 'Promise'],
// Inject namespace import
fs: ['fs', '*'],
// Use local module
'Object.assign': './src/helpers/object-assign.js'
})
]
};The plugin works by:
Creates a Rollup plugin instance configured with injection mappings.
/**
* Creates a Rollup plugin for injecting import statements
* @param options - Configuration object defining injection mappings (required)
* @returns Rollup plugin object with transform method
* @throws Error if options parameter is missing, null, or undefined
*/
function inject(options: RollupInjectOptions): Plugin;Usage Example:
import inject from '@rollup/plugin-inject';
const plugin = inject({
$: 'jquery',
Promise: ['es6-promise', 'Promise']
});Configuration interface for the inject plugin.
interface RollupInjectOptions {
/** String-to-injection mappings for global variables */
[str: string]: Injectment | RollupInjectOptions['include'] | RollupInjectOptions['exclude'] | RollupInjectOptions['sourceMap'] | RollupInjectOptions['modules'];
/** File inclusion patterns (picomatch patterns) */
include?: string | RegExp | ReadonlyArray<string | RegExp> | null;
/** File exclusion patterns (picomatch patterns) */
exclude?: string | RegExp | ReadonlyArray<string | RegExp> | null;
/** Enable/disable source map generation (default: true) */
sourceMap?: boolean;
/** Separate injection mappings object */
modules?: { [str: string]: Injectment };
}Note: The plugin also supports the sourcemap option (alternative spelling of sourceMap) for backward compatibility, but sourceMap is preferred.
Configuration Examples:
// Basic injection mapping
{
$: 'jquery',
_: 'lodash'
}
// With file filtering
{
include: ['src/**/*.js'],
exclude: ['**/*.test.js'],
$: 'jquery'
}
// Using modules property
{
sourceMap: false,
modules: {
$: 'jquery',
Promise: ['es6-promise', 'Promise']
}
}
// Mixed approach (direct + modules)
{
// Direct mappings
$: 'jquery',
// Additional configuration
include: ['src/**'],
modules: {
Promise: ['es6-promise', 'Promise']
}
}Defines the format for injection values.
type Injectment = string | [string, string];Injection Patterns:
// Default import: string format
{ $: 'jquery' }
// Generates: import $ from 'jquery';
// Named import: [module, export] format
{ Promise: ['es6-promise', 'Promise'] }
// Generates: import { Promise } from 'es6-promise';
// Namespace import: [module, '*'] format
{ fs: ['fs', '*'] }
// Generates: import * as fs from 'fs';
// Local module with default import (string format)
{ 'Object.assign': './helpers/object-assign.js' }
// Generates: import Object_assign from './helpers/object-assign.js';
// Local module with named import (array format)
{ 'Object.assign': ['./helpers/object-assign.js', 'assign'] }
// Generates: import { assign as Object_assign } from './helpers/object-assign.js';
// Keypath replacement
{ 'console.log': ['./logger', 'log'] }
// Replaces console.log calls with imported log functionThe plugin returns a Rollup plugin object with specific properties.
interface Plugin {
/** Plugin identifier */
name: 'inject';
/**
* Transform method that processes code and injects imports
* @param code - Source code string
* @param id - Module identifier/file path
* @returns Transformation result or null if file should be skipped
*/
transform(code: string, id: string): TransformResult | null;
}
interface TransformResult {
/** Transformed code string */
code: string;
/** Source map (present when sourceMap option is true, null when false) */
map?: SourceMap | null;
/** AST representation (only included when no transformations occurred) */
ast?: any;
}// Throws Error if no options provided
inject(); // Error: Missing options
inject(null); // Error: Missing options
inject(undefined); // Error: Missing options
// Valid configurations (minimum requirement is empty object)
inject({}); // Valid - empty object creates plugin with no injections
inject({ $: 'jquery' }); // Valid - injection mappingThe plugin handles files that cannot be parsed:
'PARSE_ERROR'options.include to restrict filesnull to skip transformation on parse failureExample Warning:
rollup-plugin-inject: failed to parse src/binary-file.dat.
Consider restricting the plugin to particular files via options.includeExample of prevented self-import:
// In file: src/utils.js
inject({ utils: './utils.js' });
// The plugin will NOT inject an import to itselfinject({
// Only process JavaScript files in src/
include: ['src/**/*.js'],
exclude: ['**/*.test.js', '**/*.spec.js'],
$: 'jquery',
_: 'lodash'
})inject({
// Multiple global variables from same module
Promise: ['es6-promise', 'Promise'],
'Promise.resolve': ['es6-promise', 'Promise'],
'Promise.reject': ['es6-promise', 'Promise'],
// Node.js modules
fs: ['fs', '*'],
path: ['path', '*'],
// Utility libraries
$: 'jquery',
_: 'lodash',
// Custom utilities
'utils.debounce': './src/utils/debounce.js',
'api.client': './src/api/client.js'
})inject({
// Disable source maps for better performance (both spellings supported)
sourceMap: false,
// Alternative spelling (deprecated but supported)
// sourcemap: false,
$: 'jquery'
})The plugin requires these peer and runtime dependencies:
^1.20.0||^2.0.0||^3.0.0||^4.0.0 (peer dependency, optional)^5.0.1 (runtime dependency)^2.0.2 (runtime dependency)^0.30.3 (runtime dependency)