Essential utility functions for webpack loaders, providing URL handling, filename interpolation, and hash generation capabilities.
npx @tessl/cli install tessl/npm-loader-utils@3.3.0loader-utils is a JavaScript utility library for webpack loaders, providing essential functions for URL handling, filename interpolation, and hash generation. It offers core utilities that enable webpack loaders to process resources, generate filenames, and create content hashes with high performance and zero runtime dependencies.
npm install loader-utilsconst {
urlToRequest,
isUrlRequest,
interpolateName,
getHashDigest
} = require("loader-utils");For ES modules:
import {
urlToRequest,
isUrlRequest,
interpolateName,
getHashDigest
} from "loader-utils";const loaderUtils = require("loader-utils");
// Check if URL is requestable
const url = "path/to/module.js";
if (loaderUtils.isUrlRequest(url)) {
// Convert URL to webpack module request
const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
// Generate filename with hash
const filename = loaderUtils.interpolateName(
loaderContext,
"[name].[contenthash].[ext]",
{ content: Buffer.from("file content") }
);
// Create hash digest
const hash = loaderUtils.getHashDigest(
Buffer.from("content"),
"xxhash64",
"hex",
8
);
}loader-utils is designed around four core utilities:
isUrlRequest and urlToRequest for handling resource URLs and converting them to webpack module requestsinterpolateName for template-based filename generation with placeholder substitutiongetHashDigest for creating content hashes using various algorithms and encodingsDetermines whether a URL is a requestable resource for webpack. Returns false for absolute URLs, scheme-agnostic URLs, hash URLs, and certain protocol URLs (except data URIs).
/**
* Determines if a URL is a requestable resource for webpack
* @param {string} url - The URL to test
* @returns {boolean} true if URL is requestable, false otherwise
*/
function isUrlRequest(url);Usage Examples:
// Requestable URLs (returns true)
isUrlRequest("path/to/module.js"); // true - relative path
isUrlRequest("./img.png"); // true - explicit relative
isUrlRequest("~path/to/module.js"); // true - module URL
isUrlRequest("C:\\path\\file.js"); // true - Windows absolute path
isUrlRequest("data:text/plain;base64,SGVsbG8="); // true - data URI
// Non-requestable URLs (returns false)
isUrlRequest("http://example.com"); // false - absolute HTTP URL
isUrlRequest("//example.com"); // false - scheme-agnostic URL
isUrlRequest("#gradient"); // false - hash URL
isUrlRequest("mailto:test@example.com"); // false - mailto protocolConverts resource URLs to webpack module requests with support for various URL formats.
/**
* Converts some resource URL to a webpack module request
* @param {string} url - The URL to convert
* @param {string|boolean} [root] - Root path for root-relative URLs
* @returns {string} The converted webpack module request
*/
function urlToRequest(url, root);Usage Examples:
// Basic conversion
urlToRequest("path/to/module.js"); // "./path/to/module.js"
// Module URLs (with ~)
urlToRequest("~path/to/module.js"); // "path/to/module.js"
// Root-relative URLs
urlToRequest("/path/to/module.js", "./root"); // "./root/path/to/module.js"
urlToRequest("/path/to/module.js", "~"); // "path/to/module.js"
// Windows absolute paths (preserved)
urlToRequest("C:\\path\\to\\module.js"); // "C:\\path\\to\\module.js"Interpolates filename templates using multiple placeholders and optional regular expression matching.
/**
* Interpolates a filename template using multiple placeholders
* @param {object} loaderContext - Webpack loader context object
* @param {string|function} name - Template string or function returning template
* @param {object} [options={}] - Options object with optional properties
* @param {string} [options.context] - Context path for relative path calculation
* @param {Buffer} [options.content] - Content buffer for hash generation
* @param {string} [options.regExp] - Regular expression for template matching
* @returns {string} Interpolated filename
*/
function interpolateName(loaderContext, name, options = {});Template Placeholders:
[ext] - File extension[name] - File basename[path] - File path relative to context[folder] - Parent folder name[query] - Resource query string[hash] / [contenthash] - Content hash (xxhash64 by default)[<hashType>:hash:<digestType>:<length>] - Configurable hash[N] - Nth regex capture groupUsage Examples:
// Basic filename with hash
interpolateName(loaderContext, "js/[hash].script.[ext]", { content: buffer });
// => "js/9473fdd0d880a43c21b7778d34872157.script.js"
// Custom hash algorithm and length
interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: buffer });
// => "2BKDTjl.js"
// Regex capture groups
interpolateName(loaderContext, "script-[1].[ext]", {
regExp: "page-(.*)\\.js",
content: buffer
});
// => "script-home.js" (for "page-home.js")
// Function template
interpolateName(
loaderContext,
(resourcePath, resourceQuery) => "js/[hash].script.[ext]",
{ content: buffer }
);Generates hash digest from buffer with configurable algorithm and encoding.
/**
* Generates hash digest from buffer with configurable algorithm and encoding
* @param {Buffer} buffer - Content to hash
* @param {string} [algorithm="xxhash64"] - Hash algorithm
* @param {string} [digestType="hex"] - Digest encoding
* @param {number} [maxLength=9999] - Maximum output length
* @returns {string} Hash digest
*/
function getHashDigest(buffer, algorithm, digestType, maxLength);Supported Hash Algorithms:
xxhash64 (default, WASM implementation)md4 (WASM implementation)native-md4 (Node.js crypto module)sha1, md5, sha256, sha512 (Node.js crypto module)Supported Digest Types:
hex (default)base26, base32, base36, base49, base52, base58, base62, base64, base64safeUsage Examples:
const buffer = Buffer.from("content to hash");
// Default xxhash64 with hex encoding
getHashDigest(buffer);
// => "c31e9820c001c9c4"
// SHA256 with base64 encoding, 16 characters
getHashDigest(buffer, "sha256", "base64", 16);
// => "K8VfR2jHt9QzYb3K"
// MD4 with custom length
getHashDigest(buffer, "md4", "hex", 8);
// => "d9f8b2c1"/**
* Webpack loader context object structure (relevant properties)
*/
interface LoaderContext {
/** Absolute path to the resource being processed */
resourcePath: string;
/** Query string from the resource (e.g., "?foo=bar") */
resourceQuery?: string;
/** Loader options object */
options?: {
/** Custom interpolation function */
customInterpolateName?: (url: string, name: string, options: object) => string;
};
/** Context directory for relative path resolution */
context?: string;
/** Root context directory */
rootContext?: string;
/** Current working directory */
cwd?: string;
}
/**
* Options for interpolateName function
*/
interface InterpolateNameOptions {
/** Context path for relative path calculation */
context?: string;
/** Content buffer for hash generation */
content?: Buffer;
/** Regular expression for template matching */
regExp?: string;
}urlToRequest() throws Error for invalid root parameter combinationsgetHashDigest() throws Error for unknown encoding basesinterpolateName() handles missing context gracefully, using resource path as fallbackurlToRequest() and isUrlRequest() handle Windows absolute paths correctlypath and crypto modules for core functionality