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.00
# loader-utils
1
2
loader-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.
3
4
## Package Information
5
6
- **Package Name**: loader-utils
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install loader-utils`
10
11
## Core Imports
12
13
```javascript
14
const {
15
urlToRequest,
16
isUrlRequest,
17
interpolateName,
18
getHashDigest
19
} = require("loader-utils");
20
```
21
22
For ES modules:
23
24
```javascript
25
import {
26
urlToRequest,
27
isUrlRequest,
28
interpolateName,
29
getHashDigest
30
} from "loader-utils";
31
```
32
33
## Basic Usage
34
35
```javascript
36
const loaderUtils = require("loader-utils");
37
38
// Check if URL is requestable
39
const url = "path/to/module.js";
40
if (loaderUtils.isUrlRequest(url)) {
41
// Convert URL to webpack module request
42
const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
43
44
// Generate filename with hash
45
const filename = loaderUtils.interpolateName(
46
loaderContext,
47
"[name].[contenthash].[ext]",
48
{ content: Buffer.from("file content") }
49
);
50
51
// Create hash digest
52
const hash = loaderUtils.getHashDigest(
53
Buffer.from("content"),
54
"xxhash64",
55
"hex",
56
8
57
);
58
}
59
```
60
61
## Architecture
62
63
loader-utils is designed around four core utilities:
64
65
- **URL Processing**: `isUrlRequest` and `urlToRequest` for handling resource URLs and converting them to webpack module requests
66
- **Filename Generation**: `interpolateName` for template-based filename generation with placeholder substitution
67
- **Hash Generation**: `getHashDigest` for creating content hashes using various algorithms and encodings
68
- **Performance Optimization**: WASM-based hash implementations (xxhash64, md4) for high-speed hashing operations
69
70
## Capabilities
71
72
### URL Request Validation
73
74
Determines 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).
75
76
```javascript { .api }
77
/**
78
* Determines if a URL is a requestable resource for webpack
79
* @param {string} url - The URL to test
80
* @returns {boolean} true if URL is requestable, false otherwise
81
*/
82
function isUrlRequest(url);
83
```
84
85
**Usage Examples:**
86
87
```javascript
88
// Requestable URLs (returns true)
89
isUrlRequest("path/to/module.js"); // true - relative path
90
isUrlRequest("./img.png"); // true - explicit relative
91
isUrlRequest("~path/to/module.js"); // true - module URL
92
isUrlRequest("C:\\path\\file.js"); // true - Windows absolute path
93
isUrlRequest("data:text/plain;base64,SGVsbG8="); // true - data URI
94
95
// Non-requestable URLs (returns false)
96
isUrlRequest("http://example.com"); // false - absolute HTTP URL
97
isUrlRequest("//example.com"); // false - scheme-agnostic URL
98
isUrlRequest("#gradient"); // false - hash URL
99
isUrlRequest("mailto:test@example.com"); // false - mailto protocol
100
```
101
102
### URL to Request Conversion
103
104
Converts resource URLs to webpack module requests with support for various URL formats.
105
106
```javascript { .api }
107
/**
108
* Converts some resource URL to a webpack module request
109
* @param {string} url - The URL to convert
110
* @param {string|boolean} [root] - Root path for root-relative URLs
111
* @returns {string} The converted webpack module request
112
*/
113
function urlToRequest(url, root);
114
```
115
116
**Usage Examples:**
117
118
```javascript
119
// Basic conversion
120
urlToRequest("path/to/module.js"); // "./path/to/module.js"
121
122
// Module URLs (with ~)
123
urlToRequest("~path/to/module.js"); // "path/to/module.js"
124
125
// Root-relative URLs
126
urlToRequest("/path/to/module.js", "./root"); // "./root/path/to/module.js"
127
urlToRequest("/path/to/module.js", "~"); // "path/to/module.js"
128
129
// Windows absolute paths (preserved)
130
urlToRequest("C:\\path\\to\\module.js"); // "C:\\path\\to\\module.js"
131
```
132
133
### Filename Interpolation
134
135
Interpolates filename templates using multiple placeholders and optional regular expression matching.
136
137
```javascript { .api }
138
/**
139
* Interpolates a filename template using multiple placeholders
140
* @param {object} loaderContext - Webpack loader context object
141
* @param {string|function} name - Template string or function returning template
142
* @param {object} [options={}] - Options object with optional properties
143
* @param {string} [options.context] - Context path for relative path calculation
144
* @param {Buffer} [options.content] - Content buffer for hash generation
145
* @param {string} [options.regExp] - Regular expression for template matching
146
* @returns {string} Interpolated filename
147
*/
148
function interpolateName(loaderContext, name, options = {});
149
```
150
151
**Template Placeholders:**
152
153
- `[ext]` - File extension
154
- `[name]` - File basename
155
- `[path]` - File path relative to context
156
- `[folder]` - Parent folder name
157
- `[query]` - Resource query string
158
- `[hash]` / `[contenthash]` - Content hash (xxhash64 by default)
159
- `[<hashType>:hash:<digestType>:<length>]` - Configurable hash
160
- `[N]` - Nth regex capture group
161
162
**Usage Examples:**
163
164
```javascript
165
// Basic filename with hash
166
interpolateName(loaderContext, "js/[hash].script.[ext]", { content: buffer });
167
// => "js/9473fdd0d880a43c21b7778d34872157.script.js"
168
169
// Custom hash algorithm and length
170
interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: buffer });
171
// => "2BKDTjl.js"
172
173
// Regex capture groups
174
interpolateName(loaderContext, "script-[1].[ext]", {
175
regExp: "page-(.*)\\.js",
176
content: buffer
177
});
178
// => "script-home.js" (for "page-home.js")
179
180
// Function template
181
interpolateName(
182
loaderContext,
183
(resourcePath, resourceQuery) => "js/[hash].script.[ext]",
184
{ content: buffer }
185
);
186
```
187
188
### Hash Digest Generation
189
190
Generates hash digest from buffer with configurable algorithm and encoding.
191
192
```javascript { .api }
193
/**
194
* Generates hash digest from buffer with configurable algorithm and encoding
195
* @param {Buffer} buffer - Content to hash
196
* @param {string} [algorithm="xxhash64"] - Hash algorithm
197
* @param {string} [digestType="hex"] - Digest encoding
198
* @param {number} [maxLength=9999] - Maximum output length
199
* @returns {string} Hash digest
200
*/
201
function getHashDigest(buffer, algorithm, digestType, maxLength);
202
```
203
204
**Supported Hash Algorithms:**
205
- `xxhash64` (default, WASM implementation)
206
- `md4` (WASM implementation)
207
- `native-md4` (Node.js crypto module)
208
- `sha1`, `md5`, `sha256`, `sha512` (Node.js crypto module)
209
210
**Supported Digest Types:**
211
- `hex` (default)
212
- `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`, `base64safe`
213
214
**Usage Examples:**
215
216
```javascript
217
const buffer = Buffer.from("content to hash");
218
219
// Default xxhash64 with hex encoding
220
getHashDigest(buffer);
221
// => "c31e9820c001c9c4"
222
223
// SHA256 with base64 encoding, 16 characters
224
getHashDigest(buffer, "sha256", "base64", 16);
225
// => "K8VfR2jHt9QzYb3K"
226
227
// MD4 with custom length
228
getHashDigest(buffer, "md4", "hex", 8);
229
// => "d9f8b2c1"
230
```
231
232
## Types
233
234
```javascript { .api }
235
/**
236
* Webpack loader context object structure (relevant properties)
237
*/
238
interface LoaderContext {
239
/** Absolute path to the resource being processed */
240
resourcePath: string;
241
/** Query string from the resource (e.g., "?foo=bar") */
242
resourceQuery?: string;
243
/** Loader options object */
244
options?: {
245
/** Custom interpolation function */
246
customInterpolateName?: (url: string, name: string, options: object) => string;
247
};
248
/** Context directory for relative path resolution */
249
context?: string;
250
/** Root context directory */
251
rootContext?: string;
252
/** Current working directory */
253
cwd?: string;
254
}
255
256
/**
257
* Options for interpolateName function
258
*/
259
interface InterpolateNameOptions {
260
/** Context path for relative path calculation */
261
context?: string;
262
/** Content buffer for hash generation */
263
content?: Buffer;
264
/** Regular expression for template matching */
265
regExp?: string;
266
}
267
```
268
269
## Error Handling
270
271
- `urlToRequest()` throws `Error` for invalid root parameter combinations
272
- `getHashDigest()` throws `Error` for unknown encoding bases
273
- `interpolateName()` handles missing context gracefully, using resource path as fallback
274
- Functions validate input parameters and provide descriptive error messages
275
276
## Platform Considerations
277
278
- **Windows Path Support**: Both `urlToRequest()` and `isUrlRequest()` handle Windows absolute paths correctly
279
- **Node.js Dependencies**: Uses Node.js `path` and `crypto` modules for core functionality
280
- **Performance**: WASM-based implementations for xxhash64 and md4 provide high-speed hashing
281
- **Zero Runtime Dependencies**: No external dependencies, only Node.js built-ins