0
# Utility Functions
1
2
Snowpack provides various utility functions for file management, URL resolution, package handling, path manipulation, and build system integration. These utilities support both internal operations and external plugin development.
3
4
## Capabilities
5
6
### File URL Resolution
7
8
Get URLs for files and packages within the Snowpack build system.
9
10
```typescript { .api }
11
/**
12
* Get URL for a file location
13
* @param fileLoc - File location path
14
* @param config - Snowpack configuration
15
* @returns File URL or null if not found
16
*/
17
function getUrlForFile(fileLoc: string, config: SnowpackConfig): string | null;
18
```
19
20
```typescript
21
import { getUrlForFile, loadConfiguration } from "snowpack";
22
23
const config = await loadConfiguration();
24
25
// Get URL for source file
26
const url = getUrlForFile('/src/components/Button.jsx', config);
27
// Result: "/src/components/Button.js"
28
29
// Get URL for static asset
30
const assetUrl = getUrlForFile('/public/logo.png', config);
31
// Result: "/logo.png"
32
```
33
34
### Package Preparation
35
36
Prepare packages for the build process by installing and processing dependencies.
37
38
```typescript { .api }
39
/**
40
* Prepare packages for the build process
41
* @param options - Command options with configuration
42
* @returns Promise resolving when packages are prepared
43
*/
44
function preparePackages({config}: CommandOptions): Promise<void>;
45
```
46
47
```typescript
48
import { preparePackages, loadConfiguration } from "snowpack";
49
50
const config = await loadConfiguration();
51
52
// Prepare all packages
53
await preparePackages({ config });
54
55
// Packages are now ready for development or building
56
console.log('Packages prepared successfully');
57
```
58
59
### Cache Management
60
61
Clear the Snowpack cache directory to resolve build issues.
62
63
```typescript { .api }
64
/**
65
* Clear the Snowpack cache directory
66
* @returns Promise resolving when cache is cleared
67
*/
68
function clearCache(): Promise<void>;
69
```
70
71
```typescript
72
import { clearCache } from "snowpack";
73
74
// Clear cache before build (useful for troubleshooting)
75
console.log('Clearing cache...');
76
await clearCache();
77
console.log('Cache cleared successfully');
78
```
79
80
### Lockfile Management
81
82
Read and manage the Snowpack dependency lockfile.
83
84
```typescript { .api }
85
/**
86
* Read the snowpack.deps.json lockfile
87
* @param cwd - Current working directory
88
* @returns Promise resolving to lockfile manifest or null if not found
89
*/
90
function loadLockfile(cwd: string): Promise<LockfileManifest | null>;
91
92
/**
93
* Lockfile manifest structure
94
*/
95
interface LockfileManifest {
96
/** Package dependencies with versions */
97
dependencies: {[packageName: string]: string};
98
/** Import specifier to resolved URL mapping */
99
lock: {[specifier: string]: string};
100
}
101
```
102
103
```typescript
104
import { loadLockfile } from "snowpack";
105
106
// Load lockfile from current directory
107
const lockfile = await loadLockfile(process.cwd());
108
109
if (lockfile) {
110
console.log('Dependencies:', lockfile.dependencies);
111
console.log('Import map:', lockfile.lock);
112
} else {
113
console.log('No lockfile found');
114
}
115
```
116
117
## Path and URL Utilities
118
119
### Extension Manipulation
120
121
Work with file extensions for build processing.
122
123
```typescript { .api }
124
/**
125
* Get file extension from path
126
* @param str - File path or name
127
* @returns File extension including dot
128
*/
129
function getExtension(str: string): string;
130
131
/**
132
* Check if string has specific extension
133
* @param str - File path or name
134
* @param ext - Extension to check (with or without dot)
135
* @returns True if file has the extension
136
*/
137
function hasExtension(str: string, ext: string): boolean;
138
139
/**
140
* Replace file extension
141
* @param fileName - Original file name
142
* @param oldExt - Current extension
143
* @param newExt - New extension
144
* @returns File name with new extension
145
*/
146
function replaceExtension(fileName: string, oldExt: string, newExt: string): string;
147
148
/**
149
* Add extension to file name
150
* @param fileName - File name without extension
151
* @param newExt - Extension to add
152
* @returns File name with extension
153
*/
154
function addExtension(fileName: string, newExt: string): string;
155
156
/**
157
* Remove extension from file name
158
* @param fileName - File name with extension
159
* @param oldExt - Extension to remove
160
* @returns File name without extension
161
*/
162
function removeExtension(fileName: string, oldExt: string): string;
163
```
164
165
```typescript
166
import {
167
getExtension,
168
hasExtension,
169
replaceExtension,
170
addExtension,
171
removeExtension
172
} from "snowpack";
173
174
// Extension utilities
175
const ext = getExtension('app.tsx'); // '.tsx'
176
const hasTs = hasExtension('app.tsx', 'tsx'); // true
177
const renamed = replaceExtension('app.tsx', '.tsx', '.js'); // 'app.js'
178
const withExt = addExtension('app', '.js'); // 'app.js'
179
const noExt = removeExtension('app.js', '.js'); // 'app'
180
```
181
182
### Path Manipulation
183
184
Manipulate URL and file paths for build processing.
185
186
```typescript { .api }
187
/**
188
* Add leading slash to path
189
* @param path - Path string
190
* @returns Path with leading slash
191
*/
192
function addLeadingSlash(path: string): string;
193
194
/**
195
* Add trailing slash to path
196
* @param path - Path string
197
* @returns Path with trailing slash
198
*/
199
function addTrailingSlash(path: string): string;
200
201
/**
202
* Remove leading slash from path
203
* @param path - Path string
204
* @returns Path without leading slash
205
*/
206
function removeLeadingSlash(path: string): string;
207
208
/**
209
* Remove trailing slash from path
210
* @param path - Path string
211
* @returns Path without trailing slash
212
*/
213
function removeTrailingSlash(path: string): string;
214
215
/**
216
* Calculate relative URL between two paths
217
* @param path1 - From path
218
* @param path2 - To path
219
* @returns Relative URL
220
*/
221
function relativeURL(path1: string, path2: string): string;
222
```
223
224
```typescript
225
import {
226
addLeadingSlash,
227
addTrailingSlash,
228
removeLeadingSlash,
229
removeTrailingSlash,
230
relativeURL
231
} from "snowpack";
232
233
// Path manipulation
234
const withLeading = addLeadingSlash('src/app.js'); // '/src/app.js'
235
const withTrailing = addTrailingSlash('/src'); // '/src/'
236
const noLeading = removeLeadingSlash('/src/app.js'); // 'src/app.js'
237
const noTrailing = removeTrailingSlash('/src/'); // '/src'
238
const relative = relativeURL('/src/components/', '/src/utils/'); // '../utils/'
239
```
240
241
## Import and Package Utilities
242
243
### Import Specifier Analysis
244
245
Analyze and manipulate package import specifiers.
246
247
```typescript { .api }
248
/**
249
* Parse package import specifier into name and subpath
250
* @param imp - Import specifier (e.g., "react/jsx-runtime")
251
* @returns Tuple of [packageName, subpath]
252
*/
253
function parsePackageImportSpecifier(imp: string): [string, string | null];
254
255
/**
256
* Check if specifier is a path import (local file)
257
* @param spec - Import specifier
258
* @returns True if specifier is a path import
259
*/
260
function isPathImport(spec: string): boolean;
261
262
/**
263
* Check if value is a remote URL
264
* @param val - Value to check
265
* @returns True if value is a remote URL
266
*/
267
function isRemoteUrl(val: string): boolean;
268
269
/**
270
* Check if import URL is from a specific package
271
* @param importUrl - Import URL
272
* @param packageName - Package name to check
273
* @returns True if import is from the package
274
*/
275
function isImportOfPackage(importUrl: string, packageName: string): boolean;
276
```
277
278
```typescript
279
import {
280
parsePackageImportSpecifier,
281
isPathImport,
282
isRemoteUrl,
283
isImportOfPackage
284
} from "snowpack";
285
286
// Import analysis
287
const [pkg, subpath] = parsePackageImportSpecifier('react/jsx-runtime');
288
// pkg: 'react', subpath: 'jsx-runtime'
289
290
const isLocal = isPathImport('./components/Button'); // true
291
const isPath = isPathImport('react'); // false
292
293
const isUrl = isRemoteUrl('https://cdn.skypack.dev/react'); // true
294
const isFile = isRemoteUrl('./app.js'); // false
295
296
const isReact = isImportOfPackage('/web_modules/react.js', 'react'); // true
297
```
298
299
### Dependency Resolution
300
301
Resolve package dependencies and manifests.
302
303
```typescript { .api }
304
/**
305
* Resolve dependency manifest from node_modules
306
* @param dep - Dependency name
307
* @param cwd - Current working directory
308
* @returns Tuple of [manifestPath, manifestContent] or [null, null]
309
*/
310
function resolveDependencyManifest(dep: string, cwd: string): [string | null, any | null];
311
312
/**
313
* Create install target from package specifier
314
* @param specifier - Package specifier
315
* @param all - Include all exports (default true)
316
* @returns Install target object
317
*/
318
function createInstallTarget(specifier: string, all?: boolean): InstallTarget;
319
320
/**
321
* Install target interface
322
*/
323
interface InstallTarget {
324
/** Package specifier */
325
specifier: string;
326
/** Include all exports */
327
all: boolean;
328
/** Default export */
329
default?: boolean;
330
/** Named exports */
331
namespace?: boolean;
332
}
333
```
334
335
```typescript
336
import { resolveDependencyManifest, createInstallTarget } from "snowpack";
337
338
// Resolve package manifest
339
const [manifestPath, manifest] = resolveDependencyManifest('react', process.cwd());
340
if (manifest) {
341
console.log('React version:', manifest.version);
342
console.log('Main entry:', manifest.main);
343
}
344
345
// Create install target
346
const target = createInstallTarget('react', true);
347
// { specifier: 'react', all: true }
348
```
349
350
## File System Utilities
351
352
### File Operations
353
354
Read files with automatic encoding detection and type handling.
355
356
```typescript { .api }
357
/**
358
* Read file with automatic encoding detection
359
* @param filepath - Path to file
360
* @returns Promise resolving to file contents as string or Buffer
361
*/
362
function readFile(filepath: string): Promise<string | Buffer>;
363
364
/**
365
* Check if file system events are enabled
366
* @returns True if fsevents is available (macOS)
367
*/
368
function isFsEventsEnabled(): boolean;
369
370
/**
371
* Safely delete files from build directory
372
* @param dir - Directory to clean
373
* @param config - Snowpack configuration
374
*/
375
function deleteFromBuildSafe(dir: string, config: SnowpackConfig): void;
376
```
377
378
```typescript
379
import { readFile, isFsEventsEnabled, deleteFromBuildSafe } from "snowpack";
380
381
// Read file with automatic encoding
382
const content = await readFile('./src/app.js');
383
if (typeof content === 'string') {
384
console.log('Text file:', content.length, 'characters');
385
} else {
386
console.log('Binary file:', content.length, 'bytes');
387
}
388
389
// Check file watching capabilities
390
if (isFsEventsEnabled()) {
391
console.log('Fast file watching available (macOS)');
392
}
393
394
// Clean build directory
395
deleteFromBuildSafe('./dist', config);
396
```
397
398
## Source Map Utilities
399
400
Add source map URLs to compiled code.
401
402
```typescript { .api }
403
/**
404
* Add CSS source mapping URL
405
* @param code - CSS code
406
* @param sourceMappingURL - Source map URL
407
* @returns CSS with source map comment
408
*/
409
function cssSourceMappingURL(code: string, sourceMappingURL: string): string;
410
411
/**
412
* Add JavaScript source mapping URL
413
* @param code - JavaScript code
414
* @param sourceMappingURL - Source map URL
415
* @returns JavaScript with source map comment
416
*/
417
function jsSourceMappingURL(code: string, sourceMappingURL: string): string;
418
```
419
420
```typescript
421
import { cssSourceMappingURL, jsSourceMappingURL } from "snowpack";
422
423
// Add source maps to compiled code
424
const cssWithMap = cssSourceMappingURL(
425
'.button { color: blue; }',
426
'./app.css.map'
427
);
428
// Result: '.button { color: blue; }\n/*# sourceMappingURL=./app.css.map */'
429
430
const jsWithMap = jsSourceMappingURL(
431
'export const app = "hello";',
432
'./app.js.map'
433
);
434
// Result: 'export const app = "hello";\n//# sourceMappingURL=./app.js.map'
435
```
436
437
## HTML Manipulation
438
439
Modify HTML content during build processing.
440
441
```typescript { .api }
442
/**
443
* Append HTML content to document head
444
* @param doc - HTML document string
445
* @param htmlToAdd - HTML to append to head
446
* @returns Modified HTML document
447
*/
448
function appendHtmlToHead(doc: string, htmlToAdd: string): string;
449
450
/**
451
* Check if pathname represents JavaScript
452
* @param pathname - File pathname
453
* @returns True if pathname is JavaScript
454
*/
455
function isJavaScript(pathname: string): boolean;
456
```
457
458
```typescript
459
import { appendHtmlToHead, isJavaScript } from "snowpack";
460
461
// Add content to HTML head
462
const originalHtml = '<html><head><title>App</title></head><body></body></html>';
463
const modifiedHtml = appendHtmlToHead(originalHtml, '<meta charset="utf-8">');
464
465
// Check file type
466
const isJs = isJavaScript('/src/app.js'); // true
467
const isTs = isJavaScript('/src/app.ts'); // false
468
const isJsx = isJavaScript('/src/App.jsx'); // true
469
```
470
471
## Constants and Patterns
472
473
### Regular Expressions
474
475
```typescript { .api }
476
/**
477
* Regex for detecting dotfiles
478
*/
479
const IS_DOTFILE_REGEX: RegExp;
480
481
/**
482
* HTML script tag regex
483
*/
484
const HTML_JS_REGEX: RegExp;
485
486
/**
487
* HTML style tag regex
488
*/
489
const HTML_STYLE_REGEX: RegExp;
490
491
/**
492
* CSS import regex
493
*/
494
const CSS_REGEX: RegExp;
495
496
/**
497
* Svelte/Vue script tag regex
498
*/
499
const SVELTE_VUE_REGEX: RegExp;
500
501
/**
502
* Astro frontmatter regex
503
*/
504
const ASTRO_REGEX: RegExp;
505
```
506
507
### Cache and File Names
508
509
```typescript { .api }
510
/**
511
* Default lockfile name
512
*/
513
const LOCKFILE_NAME: string; // 'snowpack.deps.json'
514
515
/**
516
* Build cache directory
517
*/
518
const BUILD_CACHE: string;
519
520
/**
521
* Global cache directory
522
*/
523
const GLOBAL_CACHE_DIR: string;
524
```
525
526
### Hot Module Replacement
527
528
```typescript { .api }
529
/**
530
* HMR client code for injection
531
*/
532
const HMR_CLIENT_CODE: string;
533
534
/**
535
* HMR error overlay code
536
*/
537
const HMR_OVERLAY_CODE: string;
538
```
539
540
## Type Utilities
541
542
```typescript { .api }
543
/**
544
* Utility type for awaited promises
545
*/
546
type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;
547
548
/**
549
* Type guard for truthy values
550
* @param item - Item to check
551
* @returns True if item is truthy
552
*/
553
function isTruthy<T>(item: T | false | null | undefined): item is T;
554
```
555
556
```typescript
557
import { isTruthy } from "snowpack";
558
559
// Filter truthy values
560
const values = ['hello', '', null, 'world', undefined, 0];
561
const truthyValues = values.filter(isTruthy);
562
// Result: ['hello', 'world']
563
```