or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-file-loader

A file loader module for webpack that resolves import/require statements on files into URLs and emits the files into the output directory.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/file-loader@6.2.x

To install, run

npx @tessl/cli install tessl/npm-file-loader@6.2.0

index.mddocs/

file-loader

file-loader is a webpack loader that resolves import/require() statements on files into URLs and emits the files into the output directory. It provides comprehensive file handling capabilities for webpack build processes, including customizable filename templates, flexible output and public path configuration, and various content hash algorithms.

Package Information

  • Package Name: file-loader
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install file-loader --save-dev

Core Imports

As a webpack loader, file-loader is used in webpack configuration rather than imported directly:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext]',
              outputPath: 'images/',
            },
          },
        ],
      },
    ],
  },
};

Basic Usage

// In your application
import logoImage from './logo.png';

// file-loader processes the file and returns the URL
console.log(logoImage); // => "/images/logo.png" or hashed filename

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|svg|pdf|txt)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[contenthash].[ext]',
              outputPath: 'assets/',
            },
          },
        ],
      },
    ],
  },
};

Architecture

file-loader operates as a webpack loader within the webpack compilation process:

  • File Processing Pipeline: Webpack identifies files matching the loader's test pattern and passes their raw content to file-loader
  • Option Validation: The loader validates all provided options against its JSON schema using schema-utils
  • Name Resolution: Uses loader-utils to interpolate filename templates with placeholders, context paths, and content hashes
  • Path Handling: Processes output and public paths, supporting both static strings and dynamic functions
  • File Emission: Emits processed files to webpack's asset system with metadata (immutability flags, source filenames)
  • Module Generation: Returns JavaScript module code that exports the final file URL, respecting ESM/CommonJS format preferences

The loader handles both development and production scenarios, supporting features like server-side rendering (emitFile: false), CDN integration (custom publicPath), and advanced filename templating with regex capture groups.

Capabilities

Main Loader Function

Processes file content and returns JavaScript module code that exports the file URL.

/**
 * Main webpack loader function that processes files
 * @param content - Raw file content as Buffer
 * @returns JavaScript module code exporting file URL
 */
function loader(content: Buffer): string;

/**
 * Indicates this loader processes raw binary content
 */
loader.raw = true;

Filename Template Configuration

Control how output files are named using customizable templates with placeholders.

interface NameOption {
  /**
   * Filename template using placeholders or function
   * @default '[contenthash].[ext]'
   */
  name?: string | ((resourcePath: string, resourceQuery: string) => string);
}

Available Placeholders:

  • [ext]: File extension
  • [name]: File basename
  • [path]: File directory path relative to context
  • [folder]: Directory containing the file
  • [query]: Query string from import (e.g., ?width=300)
  • [emoji]: Random emoji representation
  • [emoji:<length>]: Custom length emoji representation
  • [hash]: MD4 hash of content
  • [contenthash]: MD4 hash of content (alias)
  • [<hashType>:hash:<digestType>:<length>]: Custom hash format

Hash Types: md4, md5, sha1, sha256, sha512
Digest Types: hex, base26, base32, base36, base49, base52, base58, base62, base64

Output Path Configuration

Specify where files are placed in the output directory.

interface OutputPathOption {
  /**
   * Filesystem path where target files will be placed
   * @default undefined
   */
  outputPath?: string | ((url: string, resourcePath: string, context: string) => string);
}

Public Path Configuration

Configure the public URL path for generated file references.

interface PublicPathOption {
  /**
   * Custom public path for target files
   * @default __webpack_public_path__ + outputPath
   */
  publicPath?: string | ((url: string, resourcePath: string, context: string) => string);
  
  /**
   * Post-process the generated public path
   * @default undefined
   */
  postTransformPublicPath?: (publicPath: string) => string;
}

File Context Configuration

Set custom file context for path resolution.

interface ContextOption {
  /**
   * Custom file context for path resolution
   * @default webpack context
   */
  context?: string;
}

File Emission Control

Control whether files are actually written to the filesystem.

interface EmitFileOption {
  /**
   * Whether to emit files to filesystem
   * @default true
   */
  emitFile?: boolean;
}

Regular Expression Matching

Extract parts of file paths for use in filename templates.

interface RegExpOption {
  /**
   * Regular expression to capture parts of file path
   * Capture groups can be used in name template with [N] placeholders
   * @default undefined
   */
  regExp?: RegExp | string;
}

Module Format Configuration

Control the output module format. The esModule option determines whether file-loader generates ES modules (export default) or CommonJS (module.exports =) syntax.

interface ESModuleOption {
  /**
   * Generate ES modules syntax instead of CommonJS
   * @default true
   */
  esModule?: boolean;
}

Generated Output Examples:

With esModule: true (default):

export default __webpack_public_path__ + "images/logo.abc123.png";

With esModule: false:

module.exports = __webpack_public_path__ + "images/logo.abc123.png";

Path Normalization Utility

Internal utility function for cross-platform path normalization.

/**
 * Normalizes file paths for cross-platform compatibility
 * Converts backslashes to forward slashes and handles Windows namespaces
 * @param path - File path to normalize
 * @param stripTrailing - Whether to remove trailing slashes
 * @returns Normalized path string
 */
function normalizePath(path: string, stripTrailing?: boolean): string;

Complete Options Interface

interface FileLoaderOptions {
  name?: string | ((resourcePath: string, resourceQuery: string) => string);
  outputPath?: string | ((url: string, resourcePath: string, context: string) => string);
  publicPath?: string | ((url: string, resourcePath: string, context: string) => string);
  postTransformPublicPath?: (publicPath: string) => string;
  context?: string;
  emitFile?: boolean;
  regExp?: RegExp | string;
  esModule?: boolean;
}

Usage Examples

Basic File Processing

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: ['file-loader']
      }
    ]
  }
};

// In your code
import image from './photo.jpg';
// Result: image === "0dcbbaa701328ae351f.jpg"

Custom Naming with Placeholders

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[contenthash].[ext]'
            }
          }
        ]
      }
    ]
  }
};

// Input: ./images/logo.png
// Output: images/logo.a1b2c3d4.png

CDN Configuration

// webpack.config.js
module.exports = {
  output: {
    publicPath: 'https://cdn.example.com/',
  },
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[contenthash].[ext]',
              outputPath: 'images/',
            }
          }
        ]
      }
    ]
  }
};

// Result: https://cdn.example.com/images/logo.a1b2c3d4.png

Dynamic Public Path

// main.js - Set runtime public path
__webpack_public_path__ = process.env.CDN_URL + '/';

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        loader: 'file-loader',
        options: {
          name: '[name].[contenthash].[ext]',
          outputPath: 'static/assets/',
          publicPath: 'static/assets/',
          postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
        },
      },
    ],
  },
};

RegExp Capture Groups

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              regExp: /\/([a-z0-9]+)\/[a-z0-9]+\.png$/i,
              name: '[1]-[name].[ext]',
            }
          }
        ]
      }
    ]
  }
};

// Input: ./customer01/file.png
// Output: customer01-file.png

Server-Side Rendering

// webpack.config.js for server build
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              emitFile: false, // Don't write files in server build
              publicPath: '/assets/',
            }
          }
        ]
      }
    ]
  }
};

Custom Hash Configuration

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[sha512:hash:base64:7].[ext]'
            }
          }
        ]
      }
    ]
  }
};

// Result: gdyb21L.png

Function-Based Configuration

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name(resourcePath, resourceQuery) {
                if (process.env.NODE_ENV === 'development') {
                  return '[path][name].[ext]';
                }
                return '[contenthash].[ext]';
              },
              outputPath: (url, resourcePath, context) => {
                if (/images/.test(context)) {
                  return `image_output_path/${url}`;
                }
                return `output_path/${url}`;
              }
            }
          }
        ]
      }
    ]
  }
};

Types

/**
 * Main loader function signature
 */
type LoaderFunction = (content: Buffer) => string;

/**
 * Path normalization utility function signature
 */
type NormalizePathFunction = (path: string, stripTrailing?: boolean) => string;

/**
 * Name option types
 */
type NameOption = string | ((resourcePath: string, resourceQuery: string) => string);

/**
 * Path function signature for outputPath and publicPath
 */
type PathFunction = (url: string, resourcePath: string, context: string) => string;

/**
 * Post-transform function for publicPath
 */
type PostTransformFunction = (publicPath: string) => string;

/**
 * Complete options interface
 */
interface FileLoaderOptions {
  name?: NameOption;
  outputPath?: string | PathFunction;
  publicPath?: string | PathFunction;
  postTransformPublicPath?: PostTransformFunction;
  context?: string;
  emitFile?: boolean;
  regExp?: RegExp | string;
  esModule?: boolean;
}