CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rollup--plugin-image

Import JPG, PNG, GIF, SVG, and WebP files as base64 strings or DOM Image elements

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-image

A Rollup plugin that imports JPG, PNG, GIF, SVG, and WebP files directly into JavaScript modules. The plugin converts images to base64-encoded strings or DOM Image elements, making them immediately available at startup without requiring asynchronous loading.

Images are encoded using base64, which means they will be 33% larger than the size on disk. This plugin is ideal for small images where the convenience of immediate availability outweighs the 33% size increase, such as icons, logos, or UI elements that need to be available synchronously.

Package Information

  • Package Name: @rollup/plugin-image
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install @rollup/plugin-image --save-dev
  • Requirements: Node.js v14.0.0+ and Rollup v1.20.0+

Core Imports

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

For CommonJS:

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

Basic Usage

Plugin Configuration

// rollup.config.js
import image from '@rollup/plugin-image';

export default {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [image()]
};

Importing Images (Base64 Mode - Default)

// src/index.js
import logo from './rollup.png';

console.log(logo); // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."

Importing Images (DOM Mode)

// rollup.config.js with DOM mode enabled
import image from '@rollup/plugin-image';

export default {
  input: 'src/index.js',
  output: { dir: 'output', format: 'cjs' },
  plugins: [image({ dom: true })]
};
// src/index.js
import logo from './rollup.png';

document.body.appendChild(logo); // logo is now a DOM Image element

Capabilities

Plugin Factory Function

Creates a Rollup plugin instance that processes image files.

/**
 * Creates a Rollup plugin for importing image files as base64 strings or DOM elements
 * @param options - Configuration options for the plugin
 * @returns Rollup plugin object
 */
function image(options?: RollupImageOptions): Plugin;

Configuration Options

interface RollupImageOptions {
  /**
   * A picomatch pattern, or array of patterns, which specifies the files 
   * the plugin should operate on. By default all files are targeted.
   */
  include?: FilterPattern;
  
  /**
   * A picomatch pattern, or array of patterns, which specifies the files 
   * the plugin should ignore. By default no files are ignored.
   */
  exclude?: FilterPattern;
  
  /**
   * If true, generates DOM Image elements instead of base64 strings.
   * If false (default), generates base64 data URI strings.
   * @default false
   */
  dom?: boolean;
}

Usage Examples:

// Basic usage - processes all image files
export default {
  plugins: [image()]
};

// Filter specific files
export default {
  plugins: [image({
    include: ['**/*.png', '**/*.jpg'],
    exclude: ['**/test-images/**']
  })]
};

// DOM mode for browser usage
export default {
  plugins: [image({ dom: true })]
};

Plugin Object

The plugin returns a standard Rollup plugin object with the following structure:

interface Plugin {
  /** Plugin identifier */
  name: 'image';
  
  /** 
   * Load hook that processes image files and returns transformed code
   * @param id - File path being loaded
   * @returns Transformed JavaScript code or null if file should be ignored
   */
  load(id: string): string | null;
  
  /** 
   * Adds a file to Rollup's watch list (called internally by load hook)
   * @param id - File path to watch for changes
   */
  addWatchFile?(id: string): void;
}

Supported File Types

The plugin processes files with the following extensions and MIME types:

  • JPG/JPEG (image/jpeg): .jpg, .jpeg
  • PNG (image/png): .png
  • GIF (image/gif): .gif
  • SVG (image/svg+xml): .svg
  • WebP (image/webp): .webp

Export Modes

Base64 Mode (Default)

When dom: false (default), imported images are exported as base64-encoded data URI strings:

import logo from './image.png';
// logo is a string: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."

// Can be used in CSS, HTML, or canvas contexts
const img = new Image();
img.src = logo;

DOM Mode

When dom: true, imported images are exported as ready-to-use DOM Image elements:

import logo from './image.png';
// logo is an Image object that can be directly appended to DOM

document.body.appendChild(logo);
// or
canvas.getContext('2d').drawImage(logo, 0, 0);

Types

Core Types

import type { FilterPattern } from '@rollup/pluginutils';
import type { Plugin } from 'rollup';

type FilterPattern = string | RegExp | Array<string | RegExp> | null;

Dependencies

  • @rollup/pluginutils: Provides createFilter() utility and FilterPattern type
  • mini-svg-data-uri: Optimizes SVG data URI encoding for smaller output
  • Node.js built-ins: fs.readFileSync() for file reading, path.extname() for extension detection

Error Handling

The plugin handles various error conditions during the build process:

File Processing Errors

  • Non-image files: Files that don't match supported extensions (.jpg, .jpeg, .png, .gif, .svg, .webp) are ignored (plugin returns null)
  • Filtered files: Files that don't pass the include/exclude filter are ignored (plugin returns null)
  • Missing files: If an imported image file doesn't exist, Rollup will throw a build error with the message "Could not load [file path]"
  • Corrupted files: Invalid or corrupted image files will cause fs.readFileSync() to throw system errors, failing the build

Common Error Messages

Error: Could not load ./path/to/image.png (imported by src/index.js)

This occurs when the image file doesn't exist at the specified path.

ENOENT: no such file or directory, open './path/to/image.png'

System error when the file cannot be read from disk.

Error Prevention

  • Ensure all imported image files exist in the correct relative paths
  • Use appropriate include/exclude patterns to avoid processing non-image files
  • Verify file permissions allow reading by the build process

Performance Considerations

  • Size Impact: Base64 encoding increases file size by approximately 33%
  • Memory Usage: All images are loaded into memory during build time
  • Build Performance: Large images or many images can slow down the build process
  • Runtime Performance: Images are immediately available without network requests
  • Best Practice: Use for small images (icons, logos) rather than large photos or assets
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@rollup/plugin-image@3.0.x
Publish Source
CLI
Badge
tessl/npm-rollup--plugin-image badge