CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rollup--plugin-inject

Rollup plugin that scans modules for global variables and injects import statements where necessary

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

@rollup/plugin-inject

The @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.

Package Information

  • Package Name: @rollup/plugin-inject
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install @rollup/plugin-inject --save-dev

Core Imports

import inject from '@rollup/plugin-inject';

For CommonJS:

const inject = require('@rollup/plugin-inject');

Basic Usage

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'
    })
  ]
};

Architecture

The plugin works by:

  1. Code Scanning: Uses AST parsing to scan modules for global variable references
  2. Reference Detection: Identifies which global variables are used but not locally defined
  3. Import Generation: Automatically generates the appropriate import statements
  4. Code Transformation: Injects imports at the top of modules and replaces global references

Capabilities

Plugin Factory Function

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 Options

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']
  }
}

Injection Value Types

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 function

Plugin Object Properties

The 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;
}

Error Handling

Configuration Errors

// 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 mapping

Parse Errors

The plugin handles files that cannot be parsed:

  • Issues warning with code 'PARSE_ERROR'
  • Suggests using options.include to restrict files
  • Returns null to skip transformation on parse failure
  • Does not throw errors for unparseable files

Example Warning:

rollup-plugin-inject: failed to parse src/binary-file.dat. 
Consider restricting the plugin to particular files via options.include

Module Resolution

  • Self-import prevention: Modules cannot inject imports to themselves (returns false silently)
  • Path normalization: Handles Windows path separators automatically (converts backslashes to forward slashes)
  • Module support: Supports relative and absolute module paths
  • Format support: Works with both CommonJS and ES modules

Example of prevented self-import:

// In file: src/utils.js
inject({ utils: './utils.js' });
// The plugin will NOT inject an import to itself

Advanced Usage Patterns

File Filtering

inject({
  // Only process JavaScript files in src/
  include: ['src/**/*.js'],
  exclude: ['**/*.test.js', '**/*.spec.js'],
  
  $: 'jquery',
  _: 'lodash'
})

Complex Injection Mappings

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'
})

Source Map Control

inject({
  // Disable source maps for better performance (both spellings supported)
  sourceMap: false,
  // Alternative spelling (deprecated but supported)
  // sourcemap: false,
  
  $: 'jquery'
})

Dependencies

The plugin requires these peer and runtime dependencies:

  • Rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 (peer dependency, optional)
  • @rollup/pluginutils: ^5.0.1 (runtime dependency)
  • estree-walker: ^2.0.2 (runtime dependency)
  • magic-string: ^0.30.3 (runtime dependency)
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@rollup/plugin-inject@5.0.x
Publish Source
CLI
Badge
tessl/npm-rollup--plugin-inject badge