loader-utils

raw JSON →
3.3.1 verified Sat Apr 25 auth: no javascript

Utility library for webpack loaders providing functions like urlToRequest, interpolateName, getHashDigest, and isUrlRequest. Version 3.3.1 is current stable, with ongoing maintenance from webpack. Key differentiators: it's the official utility set for webpack loader authors, handling URL resolution, filename templating with hashing (supports xxhash64, sha1, sha256, sha512, md4, md5), and multiple digest formats including hex, base26, base32, base36, base49, base52, base58, base62, base64, and base64safe. Compared to similar utilities, it integrates directly with webpack's loader context.

error TypeError: loaderUtils.getOptions is not a function
cause getOptions was removed in v3.x.
fix
Use loaderContext.getOptions() instead.
error Error: Cannot find module 'loader-utils/parseQuery'
cause parseQuery is no longer exported in v3.x.
fix
Remove the import; use built-in URL parser or query string splitting.
error Warning: [contenthash] is deprecated, use [fullhash] instead
cause Using [contenthash] in webpack 5+ but loader-utils interpolateName uses its own hashing.
fix
Use [fullhash] in webpack configuration for full chunk hash, or use [contenthash:xxhash64:hex] in loader-utils.
breaking Prototype pollution vulnerability in versions <=2.0.2 and <=1.4.0. CVE-2022-37601.
fix Upgrade to v2.0.4+ or v3.x.
breaking ReDoS vulnerability in versions <3.2.1, <2.0.4, <1.4.2.
fix Upgrade to latest version in each major: v3.3.1, v2.0.4, v1.4.2.
deprecated getOptions has been deprecated in v3.x. Use loaderContext.getOptions() instead.
fix Replace getOptions calls with loaderContext.getOptions() or use webpack's built-in.
deprecated parseQuery has been deprecated. Use URLSearchParams or the standard query parser.
fix Replace parseQuery with new URLSearchParams(query).
gotcha interpolateName's [hash] uses xxhash64 by default in v3+. Previous versions used md4. This can cause unexpected hash output differences when upgrading.
fix Specify hash type explicitly, e.g., [hash:md4:hex] for backward compatibility.
gotcha urlToRequest with root starting with '~' now treats it as module request. Previously only URL starting with '~' was treated as module. Behavior changed subtly in v3.
fix Review usages where root parameter is passed to urlToRequest.
npm install loader-utils
yarn add loader-utils
pnpm add loader-utils

Demonstrates importing and using urlToRequest, isUrlRequest, and interpolateName in a webpack loader.

import { interpolateName, urlToRequest, isUrlRequest } from 'loader-utils';

function myLoader(loaderContext, content) {
  if (isUrlRequest(content)) {
    const request = urlToRequest(content, '~');
    // ...
  }
  const name = interpolateName(loaderContext, '[name].[contenthash:hex:8].[ext]', { content: Buffer.from(content) });
  return name;
}