0
# Build System
1
2
The Snowpack build system transforms your unbundled development application into optimized production assets. It processes files through the plugin pipeline, handles dependency bundling, and optionally integrates with production bundlers for optimization.
3
4
## Capabilities
5
6
### Production Building
7
8
Build the application for production deployment with optimization and bundling.
9
10
```typescript { .api }
11
/**
12
* Build the project for production
13
* @param commandOptions - Configuration and lockfile options
14
* @returns Promise resolving to build result with file change monitoring
15
*/
16
function build(commandOptions: CommandOptions): Promise<SnowpackBuildResult>;
17
```
18
19
```typescript
20
import { build, loadConfiguration } from "snowpack";
21
22
// Basic production build
23
const config = await loadConfiguration();
24
const result = await build({ config });
25
26
// Build with lockfile
27
const lockfile = await loadLockfile(process.cwd());
28
const result = await build({ config, lockfile });
29
30
console.log('Production build completed');
31
```
32
33
### Watch Mode Building
34
35
Build with file watching for continuous development-like building.
36
37
```typescript { .api }
38
/**
39
* Build result interface for production builds
40
*/
41
interface SnowpackBuildResult {
42
/** Register callback for file changes (watch mode only) */
43
onFileChange: (callback: OnFileChangeCallback) => void;
44
/** Shutdown build process */
45
shutdown(): Promise<void>;
46
}
47
```
48
49
```typescript
50
// Enable watch mode in configuration
51
const config = createConfiguration({
52
buildOptions: {
53
watch: true,
54
out: 'dist'
55
}
56
});
57
58
const result = await build({ config });
59
60
// Handle file changes during watch mode
61
result.onFileChange(({ filePath }) => {
62
console.log(`File rebuilt: ${filePath}`);
63
});
64
65
// Shutdown watch mode
66
process.on('SIGINT', async () => {
67
await result.shutdown();
68
process.exit(0);
69
});
70
```
71
72
### Build Pipeline
73
74
The build process follows these steps:
75
76
1. **Clean Directory** - Remove previous build output (if enabled)
77
2. **Mount Files** - Copy static files from mount points
78
3. **Build Files** - Process files through plugin pipeline
79
4. **Build Dependencies** - Bundle and optimize dependencies
80
5. **Write to Disk** - Output processed files
81
6. **Optimize** - Run production optimization (if not in watch mode)
82
7. **Cleanup** - Perform post-build cleanup
83
84
```typescript
85
// The build process automatically handles:
86
// - TypeScript compilation
87
// - JSX transformation
88
// - CSS processing
89
// - Asset optimization
90
// - Import resolution
91
// - Plugin transformations
92
```
93
94
## Build Configuration
95
96
The build system behavior is controlled through the `buildOptions` section of the Snowpack configuration:
97
98
```typescript { .api }
99
/**
100
* Build system options
101
*/
102
interface BuildOptions {
103
/** Output directory */
104
out: string;
105
/** Base URL for assets */
106
baseUrl: string;
107
/** Meta URL path for imports */
108
metaUrlPath: string;
109
/** Cache directory path */
110
cacheDirPath: string;
111
/** Clean output directory before build */
112
clean: boolean;
113
/** Generate source maps */
114
sourcemap: 'inline' | false | undefined;
115
/** Enable watch mode */
116
watch: boolean;
117
/** Generate HTML fragments */
118
htmlFragments: boolean;
119
/** JSX factory function */
120
jsxFactory: string | undefined;
121
/** JSX fragment function */
122
jsxFragment: string | undefined;
123
/** JSX import injection */
124
jsxInject: string | undefined;
125
/** Enable server-side rendering */
126
ssr: boolean;
127
/** Resolve proxy imports */
128
resolveProxyImports: boolean;
129
}
130
```
131
132
```typescript
133
// Example build configuration
134
const config = createConfiguration({
135
buildOptions: {
136
out: 'dist',
137
baseUrl: '/',
138
clean: true,
139
sourcemap: 'inline',
140
watch: false,
141
ssr: false,
142
jsxFactory: 'React.createElement',
143
jsxFragment: 'React.Fragment'
144
}
145
});
146
147
const result = await build({ config });
148
```
149
150
## Optimization
151
152
Production builds can be optimized using bundlers and minifiers through the optimize configuration:
153
154
```typescript { .api }
155
/**
156
* Production optimization options
157
*/
158
interface OptimizeOptions {
159
/** Entry points for bundling */
160
entrypoints: 'auto' | string[] | ((options: {files: string[]}) => string[]);
161
/** Enable module preloading */
162
preload: boolean;
163
/** Enable bundling */
164
bundle: boolean;
165
/** esbuild loader configuration */
166
loader?: {[ext: string]: Loader};
167
/** Source map generation */
168
sourcemap: boolean | 'both' | 'inline' | 'external';
169
/** Enable code splitting */
170
splitting: boolean;
171
/** Enable tree shaking */
172
treeshake: boolean;
173
/** Generate build manifest */
174
manifest: boolean;
175
/** Enable minification */
176
minify: boolean;
177
/** Target environment */
178
target: 'es2020' | 'es2019' | 'es2018' | 'es2017';
179
}
180
```
181
182
```typescript
183
// Example optimization configuration
184
const config = createConfiguration({
185
optimize: {
186
bundle: true,
187
minify: true,
188
treeshake: true,
189
splitting: true,
190
sourcemap: 'external',
191
target: 'es2020',
192
entrypoints: ['src/index.js'],
193
preload: true,
194
manifest: true
195
}
196
});
197
198
const result = await build({ config });
199
```
200
201
## Mount Points
202
203
Mount points define how directories are mapped to URLs in the built application:
204
205
```typescript { .api }
206
/**
207
* Mount point configuration
208
*/
209
interface MountEntry {
210
/** URL path where directory is mounted */
211
url: string;
212
/** Serve files statically without processing */
213
static: boolean;
214
/** Enable file resolution */
215
resolve: boolean;
216
/** Include dotfiles */
217
dot: boolean;
218
}
219
```
220
221
```typescript
222
// Example mount configuration
223
const config = createConfiguration({
224
mount: {
225
// Mount src/ directory to root URL with processing
226
'src': { url: '/', static: false, resolve: true },
227
// Mount public/ directory statically
228
'public': { url: '/', static: true, resolve: false },
229
// Mount assets/ to /assets/ URL
230
'assets': { url: '/assets', static: true, resolve: false }
231
}
232
});
233
```
234
235
## Built Files
236
237
The build system processes different file types through appropriate transformations:
238
239
### JavaScript/TypeScript Files
240
- Compiled to ES modules
241
- Import statements resolved
242
- Plugin transformations applied
243
- Source maps generated (if enabled)
244
245
### CSS Files
246
- Processed through PostCSS
247
- CSS Modules supported
248
- Import resolution
249
- Minification (if optimize enabled)
250
251
### Static Assets
252
- Copied to output directory
253
- URL rewriting for imports
254
- Optional optimization
255
256
### HTML Files
257
- Import resolution in script tags
258
- Base URL rewriting
259
- Fragment mode support
260
261
## File Extensions
262
263
The build system handles these file extensions by default:
264
265
```typescript { .api }
266
/**
267
* Scannable file extensions for import analysis
268
*/
269
type ScannableExt =
270
| '.astro'
271
| '.cjs'
272
| '.css'
273
| '.html'
274
| '.interface'
275
| '.js'
276
| '.jsx'
277
| '.less'
278
| '.mjs'
279
| '.sass'
280
| '.scss'
281
| '.svelte'
282
| '.ts'
283
| '.tsx'
284
| '.vue';
285
```
286
287
## Build Cache
288
289
Snowpack maintains a build cache to speed up subsequent builds:
290
291
```typescript
292
// Cache is automatically managed but can be cleared
293
await clearCache();
294
295
// Cache location is configurable
296
const config = createConfiguration({
297
buildOptions: {
298
cacheDirPath: './custom-cache'
299
}
300
});
301
```
302
303
## Error Handling
304
305
Build errors are handled gracefully with detailed error reporting:
306
307
```typescript
308
try {
309
const result = await build({ config });
310
} catch (error) {
311
console.error('Build failed:', error.message);
312
console.error('Stack trace:', error.stack);
313
process.exit(1);
314
}
315
```
316
317
## Integration with Bundlers
318
319
Snowpack can integrate with traditional bundlers for production optimization:
320
321
```typescript
322
// Example webpack plugin integration
323
const config = createConfiguration({
324
plugins: [
325
'@snowpack/plugin-webpack'
326
],
327
optimize: {
328
bundle: true,
329
minify: true
330
}
331
});
332
```