0
# Snowpack
1
2
Snowpack is a lightning-fast frontend build tool designed to leverage JavaScript's native ESM (ES Module) system as an alternative to heavier bundlers like webpack or Parcel. It provides near-instantaneous dev server startup (50ms or less), instant browser updates through hot module replacement, and out-of-the-box support for TypeScript, JSX, CSS Modules, and other modern web technologies. The tool focuses on unbundled development where each file is built individually and served directly to the browser, eliminating the need for complex bundling during development while still supporting production optimization through integration with traditional bundlers.
3
4
## Package Information
5
6
- **Package Name**: snowpack
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install snowpack`
10
11
## Core Imports
12
13
```typescript
14
import {
15
startServer,
16
build,
17
loadConfiguration,
18
createConfiguration,
19
clearCache,
20
logger
21
} from "snowpack";
22
```
23
24
For CommonJS:
25
```javascript
26
const {
27
startServer,
28
build,
29
loadConfiguration,
30
createConfiguration,
31
clearCache,
32
logger
33
} = require("snowpack");
34
```
35
36
## Basic Usage
37
38
```typescript
39
import { startServer, loadConfiguration } from "snowpack";
40
41
// Start development server
42
const config = await loadConfiguration();
43
const server = await startServer({ config });
44
45
console.log(`Dev server running on port ${server.port}`);
46
```
47
48
## Capabilities
49
50
### Development Server
51
52
Core development server functionality providing instant file building, hot module replacement, and unbundled development.
53
54
```typescript { .api }
55
/**
56
* Start the Snowpack development server
57
* @param commandOptions - Configuration and lockfile options
58
* @param options - Optional server configuration
59
* @returns Promise resolving to development server instance
60
*/
61
function startServer(
62
commandOptions: CommandOptions,
63
options?: {
64
isDev?: boolean;
65
isWatch?: boolean;
66
preparePackages?: boolean;
67
}
68
): Promise<SnowpackDevServer>;
69
```
70
71
[Development Server](./development-server.md)
72
73
### Build System
74
75
Production build functionality for optimizing and bundling applications for deployment.
76
77
```typescript { .api }
78
/**
79
* Build the project for production
80
* @param commandOptions - Configuration and lockfile options
81
* @returns Promise resolving to build result with file change monitoring
82
*/
83
function build(commandOptions: CommandOptions): Promise<SnowpackBuildResult>;
84
```
85
86
[Build System](./build-system.md)
87
88
### Configuration Management
89
90
Configuration loading, validation, and management functionality for customizing Snowpack behavior.
91
92
```typescript { .api }
93
/**
94
* Load and validate Snowpack configuration from file system
95
* @param overrides - Optional configuration overrides
96
* @param configPath - Optional path to config file
97
* @returns Promise resolving to validated configuration
98
*/
99
function loadConfiguration(overrides?: SnowpackUserConfig, configPath?: string): Promise<SnowpackConfig>;
100
101
/**
102
* Create a Snowpack configuration object with defaults
103
* @param config - Optional partial configuration
104
* @returns Complete configuration with defaults applied
105
*/
106
function createConfiguration(config?: SnowpackUserConfig): SnowpackConfig;
107
```
108
109
[Configuration Management](./configuration.md)
110
111
### Plugin System
112
113
Plugin architecture for extending Snowpack with custom file processing, transformations, and build steps.
114
115
```typescript { .api }
116
/**
117
* Plugin interface for extending Snowpack functionality
118
*/
119
interface SnowpackPlugin {
120
/** Plugin name */
121
name: string;
122
/** File resolution configuration */
123
resolve?: {
124
input: string[];
125
output: string[];
126
};
127
/** Load files matching resolve.input */
128
load?(options: PluginLoadOptions): Promise<PluginLoadResult | string | null | undefined | void>;
129
/** Transform files matching resolve.input */
130
transform?(options: PluginTransformOptions): Promise<PluginTransformResult | string | null | undefined | void>;
131
/** Run commands unrelated to file building */
132
run?(options: PluginRunOptions): Promise<unknown>;
133
/** Optimize the entire built application */
134
optimize?(options: PluginOptimizeOptions): Promise<void>;
135
/** Cleanup long-running instances before exit */
136
cleanup?(): void | Promise<void>;
137
/** Known entrypoints that should be installed */
138
knownEntrypoints?: string[];
139
/** Modify Snowpack configuration */
140
config?(snowpackConfig: SnowpackConfig): void;
141
/** Handle file changes during development */
142
onChange?({filePath}: {filePath: string}): void;
143
/** (internal interface, not set by the user) Mark a file as changed */
144
markChanged?(file: string): void;
145
}
146
```
147
148
[Plugin System](./plugins.md)
149
150
### Command Line Interface
151
152
CLI commands and options for project management, development, and building.
153
154
```typescript { .api }
155
/**
156
* Main CLI entry point
157
* @param args - Command line arguments
158
* @returns Promise resolving when command completes
159
*/
160
function cli(args: string[]): Promise<void>;
161
```
162
163
[Command Line Interface](./cli.md)
164
165
### Utility Functions
166
167
Helper functions for file management, URL resolution, and package handling.
168
169
```typescript { .api }
170
/**
171
* Get URL for a file location
172
* @param fileLoc - File location path
173
* @param config - Snowpack configuration
174
* @returns File URL or null if not found
175
*/
176
function getUrlForFile(fileLoc: string, config: SnowpackConfig): string | null;
177
178
/**
179
* Prepare packages for the build process
180
* @param options - Command options with configuration
181
* @returns Promise resolving when packages are prepared
182
*/
183
function preparePackages({config}: CommandOptions): Promise<void>;
184
185
/**
186
* Clear the Snowpack cache directory
187
* @returns Promise resolving when cache is cleared
188
*/
189
function clearCache(): Promise<void>;
190
191
/**
192
* Read the snowpack.deps.json lockfile
193
* @param cwd - Current working directory
194
* @returns Promise resolving to lockfile manifest or null
195
*/
196
function loadLockfile(cwd: string): Promise<LockfileManifest | null>;
197
```
198
199
[Utility Functions](./utilities.md)
200
201
## Core Types
202
203
### Configuration Types
204
205
```typescript { .api }
206
/**
207
* Main Snowpack configuration object
208
*/
209
interface SnowpackConfig {
210
/** Project root directory */
211
root: string;
212
/** Build mode */
213
mode: 'test' | 'development' | 'production';
214
/** Workspace root directory */
215
workspaceRoot?: string | false;
216
/** Configuration extension */
217
extends?: string;
218
/** Files to exclude from processing */
219
exclude: string[];
220
/** Environment variables */
221
env?: Record<string, string | boolean | undefined>;
222
/** Directory mount points */
223
mount: Record<string, MountEntry>;
224
/** Import aliases */
225
alias: Record<string, string>;
226
/** Loaded plugins */
227
plugins: SnowpackPlugin[];
228
/** Dependency mappings */
229
dependencies: Record<string, string>;
230
/** Development server options */
231
devOptions: {
232
secure: boolean | {cert: string | Buffer; key: string | Buffer};
233
hostname: string;
234
port: number;
235
openUrl?: string;
236
open?: string;
237
output?: 'stream' | 'dashboard';
238
hmr?: boolean;
239
hmrDelay: number;
240
hmrPort: number | undefined;
241
hmrErrorOverlay: boolean;
242
tailwindConfig?: string;
243
};
244
/** Build options */
245
buildOptions: {
246
out: string;
247
baseUrl: string;
248
metaUrlPath: string;
249
cacheDirPath: string;
250
clean: boolean;
251
sourcemap: 'inline' | false | undefined;
252
watch: boolean;
253
htmlFragments: boolean;
254
jsxFactory: string | undefined;
255
jsxFragment: string | undefined;
256
jsxInject: string | undefined;
257
ssr: boolean;
258
resolveProxyImports: boolean;
259
};
260
/** Test options */
261
testOptions: {
262
files: string[];
263
};
264
/** Package source options */
265
packageOptions: PackageOptionsLocal | PackageOptionsRemote;
266
/** Production optimization options */
267
optimize?: OptimizeOptions;
268
/** Route configuration */
269
routes: RouteConfigObject[];
270
/** Experimental features */
271
experiments: {};
272
/** File extension mappings */
273
_extensionMap: Record<string, string[]>;
274
}
275
276
/**
277
* User-provided configuration (partial of SnowpackConfig)
278
*/
279
interface SnowpackUserConfig {
280
root?: string;
281
mode?: SnowpackConfig['mode'];
282
workspaceRoot?: string;
283
install?: string[];
284
env?: Record<string, string>;
285
extends?: string;
286
exclude?: string[];
287
mount?: Record<string, string | Partial<MountEntry>>;
288
alias?: Record<string, string>;
289
plugins?: (string | [string, any])[];
290
dependencies?: Record<string, string>;
291
devOptions?: Partial<{
292
secure: boolean | {cert: string | Buffer; key: string | Buffer};
293
hostname: string;
294
port: number;
295
openUrl?: string;
296
open?: string;
297
output?: 'stream' | 'dashboard';
298
hmr?: boolean;
299
hmrDelay: number;
300
hmrPort: number | undefined;
301
hmrErrorOverlay: boolean;
302
tailwindConfig?: string;
303
}>;
304
buildOptions?: Partial<{
305
out: string;
306
baseUrl: string;
307
metaUrlPath: string;
308
cacheDirPath: string;
309
clean: boolean;
310
sourcemap: 'inline' | false | undefined;
311
watch: boolean;
312
htmlFragments: boolean;
313
jsxFactory: string | undefined;
314
jsxFragment: string | undefined;
315
jsxInject: string | undefined;
316
ssr: boolean;
317
resolveProxyImports: boolean;
318
}>;
319
testOptions?: Partial<{
320
files: string[];
321
}>;
322
packageOptions?: Partial<SnowpackConfig['packageOptions']>;
323
optimize?: Partial<SnowpackConfig['optimize']>;
324
routes?: Pick<RouteConfigObject, 'src' | 'dest' | 'match'>[];
325
experiments?: {};
326
}
327
328
/**
329
* Command options passed to commands
330
*/
331
interface CommandOptions {
332
/** Snowpack configuration */
333
config: SnowpackConfig;
334
/** Optional lockfile manifest */
335
lockfile?: LockfileManifest | null;
336
}
337
```
338
339
### Server Types
340
341
```typescript { .api }
342
/**
343
* Development server instance
344
*/
345
interface SnowpackDevServer {
346
/** Server port number */
347
port: number;
348
/** Hot module replacement engine */
349
hmrEngine?: EsmHmrEngine;
350
/** Raw HTTP server instance */
351
rawServer?: http.Server | http2.Http2Server | undefined;
352
/** Load URL with options */
353
loadUrl: {
354
(reqUrl: string, opt?: LoadUrlOptions | undefined): Promise<LoadResult<Buffer | string> | undefined>;
355
(reqUrl: string, opt: LoadUrlOptions & {encoding: BufferEncoding}): Promise<LoadResult<string> | undefined>;
356
(reqUrl: string, opt: LoadUrlOptions & {encoding: null}): Promise<LoadResult<Buffer> | undefined>;
357
};
358
/** Handle HTTP requests */
359
handleRequest: (req: http.IncomingMessage, res: http.ServerResponse, options?: {handleError?: boolean}) => Promise<void>;
360
/** Send response file */
361
sendResponseFile: (req: http.IncomingMessage, res: http.ServerResponse, result: LoadResult) => void;
362
/** Get server runtime for SSR */
363
getServerRuntime: (options?: {invalidateOnChange?: boolean}) => ServerRuntime;
364
/** Send error response */
365
sendResponseError: (req: http.IncomingMessage, res: http.ServerResponse, status: number) => void;
366
/** Get URL for file location */
367
getUrlForFile: (fileLoc: string) => string | null;
368
/** Get URL for package */
369
getUrlForPackage: (packageSpec: string) => Promise<string>;
370
/** Register file change callback */
371
onFileChange: (callback: OnFileChangeCallback) => void;
372
/** Mark file as changed */
373
markChanged: (fileLoc: string) => void;
374
/** Shutdown server */
375
shutdown(): Promise<void>;
376
}
377
378
/**
379
* Build result from production build
380
*/
381
interface SnowpackBuildResult {
382
/** Register file change callback */
383
onFileChange: (callback: OnFileChangeCallback) => void;
384
/** Shutdown build process */
385
shutdown(): Promise<void>;
386
}
387
```
388
389
### Plugin Types
390
391
```typescript { .api }
392
/**
393
* Plugin factory function type
394
*/
395
type SnowpackPluginFactory<PluginOptions = object> = (
396
snowpackConfig: SnowpackConfig,
397
pluginOptions?: PluginOptions,
398
) => SnowpackPlugin;
399
400
/**
401
* Options for plugin load method
402
*/
403
interface PluginLoadOptions {
404
/** Absolute file path */
405
filePath: string;
406
/** File extension */
407
fileExt: string;
408
/** Development mode flag */
409
isDev: boolean;
410
/** HMR enabled flag */
411
isHmrEnabled: boolean;
412
/** SSR mode flag */
413
isSSR: boolean;
414
/** Package file flag */
415
isPackage: boolean;
416
}
417
418
/**
419
* Options for plugin transform method
420
*/
421
interface PluginTransformOptions {
422
/** Build file path */
423
id: string;
424
/** Source file path */
425
srcPath: string;
426
/** File extension */
427
fileExt: string;
428
/** File contents */
429
contents: string | Buffer;
430
/** Development mode flag */
431
isDev: boolean;
432
/** HMR enabled flag */
433
isHmrEnabled: boolean;
434
/** SSR mode flag */
435
isSSR: boolean;
436
/** Package file flag */
437
isPackage: boolean;
438
}
439
440
/**
441
* Plugin load result type
442
*/
443
type PluginLoadResult = SnowpackBuildMap;
444
445
/**
446
* Plugin transform result type
447
*/
448
type PluginTransformResult = {
449
contents: string;
450
map: string | RawSourceMap;
451
};
452
```
453
454
### Utility Types
455
456
```typescript { .api }
457
/**
458
* File load result
459
*/
460
interface LoadResult<T = Buffer | string> {
461
/** File contents */
462
contents: T;
463
/** Import targets found in file */
464
imports: InstallTarget[];
465
/** Original file location */
466
originalFileLoc: string | null;
467
/** Content type */
468
contentType: string | false;
469
/** Function to check if file is stale */
470
checkStale?: () => Promise<void>;
471
}
472
473
/**
474
* File change callback type
475
*/
476
type OnFileChangeCallback = ({filePath: string}) => any;
477
478
/**
479
* Import map structure
480
*/
481
interface ImportMap {
482
imports: {[specifier: string]: string};
483
}
484
485
/**
486
* Lockfile manifest structure
487
*/
488
interface LockfileManifest {
489
dependencies: {[packageName: string]: string};
490
lock: {[specifier: string]: string};
491
}
492
493
/**
494
* CLI flags interface
495
*/
496
interface CLIFlags {
497
help?: boolean;
498
version?: boolean;
499
reload?: boolean;
500
root?: string;
501
config?: string;
502
env?: string[];
503
open?: string[];
504
secure?: boolean;
505
verbose?: boolean;
506
quiet?: boolean;
507
[flag: string]: any;
508
}
509
```
510
511
## Logger
512
513
```typescript { .api }
514
/**
515
* Snowpack logger instance
516
*/
517
interface SnowpackLogger {
518
/** Log level */
519
level: LoggerLevel;
520
/** Debug log message */
521
debug(message: string, options?: LoggerOptions): void;
522
/** Info log message */
523
info(message: string, options?: LoggerOptions): void;
524
/** Warning log message */
525
warn(message: string, options?: LoggerOptions): void;
526
/** Error log message */
527
error(message: string, options?: LoggerOptions): void;
528
}
529
530
/**
531
* Logger instance for Snowpack operations
532
*/
533
const logger: SnowpackLogger;
534
535
/**
536
* Logger level type
537
*/
538
type LoggerLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
539
```
540
541
## Error Classes
542
543
```typescript { .api }
544
/**
545
* Error thrown when a file is not found during development
546
*/
547
class NotFoundError extends Error {
548
constructor(message: string);
549
}
550
```
551
552
## Deprecated Functions
553
554
```typescript { .api }
555
/**
556
* @deprecated Renamed to startServer(). Throws deprecation error.
557
*/
558
function startDevServer(): never;
559
560
/**
561
* @deprecated Renamed to build(). Throws deprecation error.
562
*/
563
function buildProject(): never;
564
565
/**
566
* @deprecated Replaced by loadConfiguration() and createConfiguration(). Throws deprecation error.
567
*/
568
function loadAndValidateConfig(): never;
569
```