CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-url-loader

A webpack loader that transforms files into base64 URIs for efficient bundling

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

URL Loader

URL Loader is a webpack loader that transforms files into base64 URIs for efficient bundling and deployment. It works as an intelligent alternative to file-loader by converting small files directly into data URLs while falling back to file-loader for larger files that exceed a configurable size limit.

Package Information

  • Package Name: url-loader
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install url-loader
  • Webpack Versions: 4.x and 5.x
  • Node.js: >= 10.13.0

Core Imports

For webpack configuration:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|svg)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
            },
          },
        ],
      },
    ],
  },
};

For programmatic usage (rare):

const urlLoader = require('url-loader');

Basic Usage

URL Loader is primarily used through webpack configuration. It automatically processes matched files during the webpack build process:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: false, // Always use base64
            },
          },
        ],
      },
      {
        test: /\.svg$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192, // 8KB threshold
              mimetype: 'image/svg+xml',
              encoding: 'base64',
            },
          },
        ],
      },
    ],
  },
};

Application code using processed assets:

import logoImage from './assets/logo.png'; // Will be base64 data URI if under limit
import iconSvg from './assets/icon.svg';   // Will be base64 data URI if under limit

// logoImage and iconSvg contain either:
// - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA... (if under limit)
// - /static/media/logo.abc123.png (if over limit, handled by fallback)

Architecture

URL Loader operates as a webpack loader with the following key components:

  • Main Loader Function: Processes file content and determines transformation strategy
  • Size-based Decision Logic: Compares file size against configurable limit
  • Data URI Generation: Converts files to base64 or other encoding formats
  • Fallback System: Delegates to another loader (typically file-loader) for large files
  • Configuration Validation: Validates all options against JSON schema

Capabilities

Main Loader Function

The primary webpack loader function that processes file content.

/**
 * Main webpack loader function - called by webpack during build
 * @param {Buffer|string} content - File content to process
 * @returns {string} JavaScript module code containing the data URI or fallback result
 */
function loader(content) {}

// Raw mode flag - indicates loader should receive Buffer instead of string
loader.raw = true;

Configuration Options

Complete configuration interface for the loader options.

interface LoaderOptions {
  /** Maximum file size for base64 transformation */
  limit?: boolean | number | string;
  /** Encoding method for data URI generation */
  encoding?: boolean | "utf8" | "utf16le" | "latin1" | "base64" | "hex" | "ascii" | "binary" | "ucs2";
  /** MIME type for the generated data URI */
  mimetype?: boolean | string;
  /** Custom data URI generator function */
  generator?: (content: Buffer, mimetype: string, encoding: string, resourcePath: string) => string;
  /** Alternative loader for files exceeding the limit */
  fallback?: string | FallbackConfig;
  /** Generate ES module syntax instead of CommonJS */
  esModule?: boolean;
}

interface FallbackConfig {
  /** Fallback loader name */
  loader: string;
  /** Options to pass to fallback loader */
  options?: object | string;
}

Limit Configuration

Controls when files are transformed to base64 vs delegated to fallback loader.

// Boolean mode
limit: true   // Always transform to base64
limit: false  // Never transform, always use fallback

// Numeric mode (bytes)
limit: 8192   // Transform files <= 8KB
limit: "10kb" // Transform files <= 10KB (string format)

Usage Examples:

// Always convert to base64 (no size limit)
{
  loader: 'url-loader',
  options: {
    limit: true
  }
}

// Never convert to base64 (always use fallback)
{
  loader: 'url-loader',
  options: {
    limit: false
  }
}

// Size-based conversion (8KB threshold)
{
  loader: 'url-loader',
  options: {
    limit: 8192
  }
}

MIME Type Configuration

Controls the MIME type included in generated data URIs.

// Boolean mode
mimetype: true  // Auto-detect from file extension
mimetype: false // Omit MIME type from data URI

// String mode
mimetype: "image/png" // Use specific MIME type

Usage Examples:

// Auto-detect MIME type
{
  loader: 'url-loader',
  options: {
    mimetype: true // Uses mime-types library
  }
}

// Specific MIME type
{
  loader: 'url-loader',
  options: {
    mimetype: 'image/svg+xml'
  }
}

// No MIME type in data URI
{
  loader: 'url-loader',
  options: {
    mimetype: false
  }
}

Encoding Configuration

Specifies how file content is encoded in the data URI.

// Boolean mode
encoding: true  // Use base64 encoding
encoding: false // No encoding (raw content)

// String mode - Node.js buffer encodings
encoding: "base64" | "utf8" | "utf16le" | "latin1" | "hex" | "ascii" | "binary" | "ucs2"

Usage Examples:

// Base64 encoding (default)
{
  loader: 'url-loader',
  options: {
    encoding: 'base64'
  }
}

// UTF-8 encoding for text files
{
  loader: 'url-loader',
  options: {
    encoding: 'utf8'
  }
}

// No encoding
{
  loader: 'url-loader',
  options: {
    encoding: false
  }
}

Custom Generator Function

Allows custom data URI generation logic.

/**
 * Custom generator function for creating data URIs
 * @param {Buffer} content - File content as Buffer
 * @param {string} mimetype - Resolved MIME type
 * @param {string} encoding - Resolved encoding method
 * @param {string} resourcePath - Full file path
 * @returns {string} Custom data URI string
 */
type GeneratorFunction = (
  content: Buffer,
  mimetype: string,
  encoding: string,
  resourcePath: string
) => string;

Usage Examples:

{
  loader: 'url-loader',
  options: {
    generator: (content, mimetype, encoding, resourcePath) => {
      // Custom logic for HTML files
      if (/\.html$/i.test(resourcePath)) {
        return `data:${mimetype},${content.toString()}`;
      }
      
      // Default behavior for other files
      return `data:${mimetype}${encoding ? `;${encoding}` : ''},${content.toString(encoding)}`;
    }
  }
}

Fallback Loader Configuration

Configures alternative loader for files exceeding the size limit.

// String format
fallback: "file-loader"
fallback: "responsive-loader"

// Object format with options
fallback: {
  loader: "file-loader",
  options: {
    name: "[name].[hash:8].[ext]",
    outputPath: "images/"
  }
}

Usage Examples:

// Simple fallback
{
  loader: 'url-loader',
  options: {
    limit: 8192,
    fallback: 'file-loader'
  }
}

// Fallback with custom options
{
  loader: 'url-loader',
  options: {
    limit: 8192,
    fallback: {
      loader: 'file-loader',
      options: {
        name: '[path][name].[ext]',
        outputPath: 'assets/'
      }
    }
  }
}

// Advanced fallback
{
  loader: 'url-loader',
  options: {
    limit: 8192,
    fallback: require.resolve('responsive-loader'),
    quality: 85 // This option passes through to responsive-loader
  }
}

ES Module Configuration

Controls output module format.

esModule: boolean // Default: true

Usage Examples:

// ES module output (default)
{
  loader: 'url-loader',
  options: {
    esModule: true
  }
}
// Generates: export default "data:image/png;base64,..."

// CommonJS output
{
  loader: 'url-loader',
  options: {
    esModule: false
  }
}
// Generates: module.exports = "data:image/png;base64,..."

Error Handling

URL Loader validates all options and throws errors for:

  • Invalid Options: Schema validation failures for malformed configuration
  • Missing Fallback: When fallback loader cannot be resolved or loaded
  • Encoding Errors: When specified encoding is not supported by Node.js
  • File System Errors: When file cannot be read during processing

Common error scenarios:

// Invalid limit type
{
  loader: 'url-loader',
  options: {
    limit: {} // Error: limit must be boolean, number, or string
  }
}

// Invalid encoding
{
  loader: 'url-loader',
  options: {
    encoding: 'invalid' // Error: unsupported encoding
  }
}

// Missing fallback loader
{
  loader: 'url-loader',
  options: {
    fallback: 'nonexistent-loader' // Error: cannot resolve loader
  }
}

Dependencies

Required Dependencies

  • loader-utils (^2.0.0): Webpack loader utilities for option parsing
  • mime-types (^2.1.27): MIME type detection from file extensions
  • schema-utils (^3.0.0): JSON schema validation for loader options

Peer Dependencies

  • webpack (^4.0.0 || ^5.0.0): Required webpack version
  • file-loader (*): Optional, used as default fallback loader

Runtime Requirements

  • Node.js: >= 10.13.0
  • Environment: Node.js server-side (webpack build process)

CommonJS and ES Module Support

URL Loader provides both CommonJS and ES module interfaces:

// CommonJS (main entry - dist/cjs.js)
const urlLoader = require('url-loader');
urlLoader.raw; // true

// ES Module (source - src/index.js)
import urlLoader, { raw } from 'url-loader/src';

Note: The ES module version is the source code and requires transpilation for older Node.js versions.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/url-loader@4.1.x
Publish Source
CLI
Badge
tessl/npm-url-loader badge