0
# Build and Compilation
1
2
Core webpack compilation functionality with support for multiple webpack versions, watch mode, and optimization for serverless deployment.
3
4
## Capabilities
5
6
### Core Build Commands
7
8
Execute webpack builds through Serverless Framework commands with enhanced functionality.
9
10
```bash { .api }
11
# Main webpack build commands
12
sls webpack # Run complete webpack build pipeline
13
sls webpack validate # Validate configuration and setup
14
sls webpack compile # Compile functions with webpack
15
sls webpack compile watch # Compile with watch mode enabled
16
sls webpack package # Package external modules and artifacts
17
18
# Global options
19
--out <path> # Specify output directory path
20
--stage <stage> # Deployment stage (affects webpack.isLocal)
21
--region <region> # AWS region for provider-specific config
22
```
23
24
**Usage Examples:**
25
26
```bash
27
# Standard build
28
sls webpack
29
30
# Build with custom output
31
sls webpack --out dist
32
33
# Validate configuration
34
sls webpack validate
35
36
# Compile with watch mode
37
sls webpack compile watch
38
```
39
40
### Enhanced Serverless Commands
41
42
Standard Serverless commands enhanced with webpack compilation capabilities.
43
44
```bash { .api }
45
# Deployment commands with webpack
46
sls package # Package service with webpack compilation
47
sls deploy # Deploy service with webpack compilation
48
sls deploy function # Deploy single function with webpack
49
50
# Local development commands
51
sls invoke local # Local invocation with webpack compilation
52
sls invoke local --watch # Local invocation with watch mode
53
sls invoke local --skip-build # Skip webpack compilation step
54
sls invoke local --webpack-use-polling <ms> # Set polling interval for file changes
55
56
# Development server commands
57
sls offline start # Start serverless-offline with webpack
58
sls offline start --webpack-no-watch # Disable webpack watch mode
59
sls offline start --skip-build # Skip initial webpack build
60
61
# Run commands
62
sls run # Run function locally with webpack
63
sls run --watch # Run with watch mode enabled
64
```
65
66
**Usage Examples:**
67
68
```bash
69
# Deploy with webpack compilation
70
sls deploy --stage production
71
72
# Local development with watch
73
sls invoke local --function hello --watch
74
75
# Offline development without watch
76
sls offline start --webpack-no-watch
77
78
# Run function with polling
79
sls invoke local --function api --webpack-use-polling 1000
80
```
81
82
### Compilation Process
83
84
The plugin integrates into Serverless lifecycle hooks for automatic webpack compilation.
85
86
```javascript { .api }
87
/**
88
* Compilation lifecycle hooks and process
89
*/
90
const compilationHooks = {
91
'before:package:createDeploymentArtifacts': ['webpack:validate', 'webpack:compile', 'webpack:package'],
92
'before:deploy:function:packageFunction': ['webpack:validate', 'webpack:compile', 'webpack:package'],
93
'before:invoke:local:invoke': ['webpack:validate', 'webpack:compile'],
94
'before:run:run': ['webpack:validate', 'webpack:compile', 'packExternalModules']
95
};
96
97
/**
98
* Internal webpack events available for plugin hooks
99
*/
100
const webpackEvents = {
101
'webpack:validate:validate': 'Configuration validation',
102
'webpack:compile:compile': 'Code compilation with webpack',
103
'webpack:compile:watch:compile': 'Watch mode compilation',
104
'webpack:package:packExternalModules': 'External module packaging',
105
'webpack:package:packageModules': 'Module optimization and packaging',
106
'webpack:package:copyExistingArtifacts': 'Artifact copying and finalization'
107
};
108
```
109
110
### Watch Mode Support
111
112
Real-time compilation with file watching for development workflows.
113
114
```javascript { .api }
115
/**
116
* Watch mode configuration and capabilities
117
*/
118
interface WatchOptions {
119
usePolling?: boolean; // Use polling instead of file system events
120
pollingInterval?: number; // Polling interval in milliseconds (default: 3000)
121
ignored?: string[]; // Patterns to ignore during watch
122
aggregateTimeout?: number; // Delay before rebuilding after changes
123
}
124
```
125
126
**Usage Examples:**
127
128
```bash
129
# Watch with polling (useful for Docker/VM environments)
130
sls invoke local --function api --watch --webpack-use-polling 1000
131
132
# Watch mode with serverless-offline
133
sls offline start
134
# Watch is enabled by default, disable with --webpack-no-watch
135
136
# Manual watch mode
137
sls webpack compile watch
138
```
139
140
### Compilation Statistics and Logging
141
142
Webpack compilation statistics and build information display.
143
144
```javascript { .api }
145
/**
146
* Build statistics configuration
147
* Can be configured in webpack.config.js stats property
148
*/
149
interface StatsOptions {
150
colors?: boolean; // Enable colored output
151
chunks?: boolean; // Show chunk information
152
modules?: boolean; // Show module information
153
assets?: boolean; // Show asset information
154
warnings?: boolean; // Show warnings
155
errors?: boolean; // Show errors
156
timings?: boolean; // Show timing information
157
}
158
```
159
160
**Usage Examples:**
161
162
```javascript
163
// webpack.config.js - Custom stats configuration
164
module.exports = {
165
entry: slsw.lib.entries,
166
target: 'node',
167
stats: {
168
colors: true,
169
chunks: false,
170
modules: false,
171
assets: true,
172
warnings: true,
173
errors: true
174
}
175
};
176
177
// Minimal stats output
178
module.exports = {
179
entry: slsw.lib.entries,
180
target: 'node',
181
stats: 'minimal'
182
};
183
```
184
185
### Multi-Function Compilation
186
187
Individual function compilation with concurrency control for optimized builds.
188
189
```javascript { .api }
190
/**
191
* Compilation concurrency and individual packaging
192
*/
193
interface CompilationOptions {
194
concurrency: number; // Number of parallel compilations (default: os.cpus().length)
195
individually: boolean; // Enable individual function packaging
196
excludeFiles: string; // Files to exclude from compilation
197
}
198
```
199
200
**Usage Examples:**
201
202
```yaml
203
# serverless.yml - Individual packaging configuration
204
package:
205
individually: true
206
207
custom:
208
webpack:
209
concurrency: 4
210
excludeFiles: 'src/**/*.test.js'
211
```
212
213
When `package.individually` is enabled, each function is compiled separately, resulting in optimized bundles containing only the code and dependencies needed for each specific function.
214
215
### Output Configuration
216
217
Webpack output configuration and directory management.
218
219
```javascript { .api }
220
/**
221
* Default output configuration applied when not specified
222
*/
223
const defaultOutput = {
224
libraryTarget: 'commonjs',
225
path: path.resolve('.webpack'),
226
filename: '[name].js'
227
};
228
229
/**
230
* Output directory management
231
*/
232
interface OutputOptions {
233
keepOutputDirectory: boolean; // Preserve .webpack directory after build
234
outputPath: string; // Custom output path (via --out option)
235
}
236
```
237
238
**Usage Examples:**
239
240
```javascript
241
// webpack.config.js - Custom output configuration
242
const path = require('path');
243
244
module.exports = {
245
entry: slsw.lib.entries,
246
target: 'node',
247
output: {
248
libraryTarget: 'commonjs',
249
path: path.resolve(__dirname, 'build'),
250
filename: '[name].js'
251
}
252
};
253
```
254
255
```yaml
256
# serverless.yml - Keep output directory
257
custom:
258
webpack:
259
keepOutputDirectory: true
260
```
261
262
### Error Handling and Debugging
263
264
Compilation error handling and debugging capabilities.
265
266
```javascript { .api }
267
/**
268
* Webpack compilation error types and handling
269
*/
270
interface CompilationError {
271
message: string;
272
file?: string;
273
line?: number;
274
column?: number;
275
stack?: string;
276
}
277
278
/**
279
* Plugin error handling
280
*/
281
class ServerlessWebpackError extends Error {
282
constructor(message: string, compilation?: any);
283
}
284
```
285
286
**Usage Examples:**
287
288
```bash
289
# Debug compilation issues
290
sls webpack validate # Check configuration
291
sls webpack compile # See detailed compilation errors
292
293
# Enable webpack debug output
294
export SLS_DEBUG=*
295
sls webpack compile
296
297
# Keep output for inspection
298
sls webpack --out debug-output
299
```
300
301
### Webpack Version Support
302
303
Support for multiple webpack versions with compatibility handling.
304
305
```javascript { .api }
306
/**
307
* Supported webpack versions and compatibility
308
*/
309
const supportedWebpackVersions = ['^3.0.0', '^4.0.0', '^5.0.0'];
310
311
/**
312
* Version-specific feature detection
313
*/
314
interface WebpackCompatibility {
315
hasModuleGraph: boolean; // Webpack 5+ ModuleGraph API
316
hasOptimization: boolean; // Webpack 4+ optimization options
317
supportsDynamicImports: boolean; // Dynamic import support
318
}
319
```
320
321
The plugin automatically detects webpack version and adapts its behavior:
322
323
- **Webpack 3**: Basic compilation and bundling support
324
- **Webpack 4**: Optimization API, mode configuration, better tree-shaking
325
- **Webpack 5**: ModuleGraph API, improved caching, asset modules
326
327
### Tree-Shaking Optimization
328
329
Webpack tree-shaking optimization for smaller bundle sizes.
330
331
```javascript { .api }
332
/**
333
* Tree-shaking optimization configuration
334
* Automatically enabled when package.individually is true
335
*/
336
interface TreeShakingOptions {
337
sideEffects: boolean | string[]; // Mark side-effect free modules
338
usedExports: boolean; // Track used exports
339
providedExports: boolean; // Track provided exports
340
}
341
```
342
343
**Usage Examples:**
344
345
```javascript
346
// webpack.config.js - Optimize for tree-shaking
347
module.exports = {
348
entry: slsw.lib.entries,
349
target: 'node',
350
mode: 'production',
351
optimization: {
352
usedExports: true,
353
sideEffects: false
354
}
355
};
356
```
357
358
```json
359
// package.json - Mark side-effect free package
360
{
361
"sideEffects": false
362
}
363
```
364
365
### Custom Webpack Loaders and Plugins
366
367
Support for custom webpack loaders and plugins in serverless environment.
368
369
```javascript { .api }
370
/**
371
* Common loader configurations for serverless development
372
*/
373
interface LoaderConfigurations {
374
babelLoader: object; // Babel transpilation
375
tsLoader: object; // TypeScript compilation
376
eslintLoader: object; // ESLint integration
377
fileLoader: object; // File asset handling
378
}
379
```
380
381
**Usage Examples:**
382
383
```javascript
384
// webpack.config.js - Common loader setup
385
const slsw = require('serverless-webpack');
386
387
module.exports = {
388
entry: slsw.lib.entries,
389
target: 'node',
390
module: {
391
rules: [
392
{
393
test: /\.js$/,
394
exclude: /node_modules/,
395
use: {
396
loader: 'babel-loader',
397
options: {
398
presets: ['@babel/preset-env']
399
}
400
}
401
},
402
{
403
test: /\.ts$/,
404
use: 'ts-loader',
405
exclude: /node_modules/
406
}
407
]
408
},
409
resolve: {
410
extensions: ['.js', '.ts']
411
}
412
};
413
```
414
415
### Build Performance Optimization
416
417
Optimization techniques for faster builds and smaller bundles.
418
419
```javascript { .api }
420
/**
421
* Performance optimization options
422
*/
423
interface PerformanceOptions {
424
concurrency: number; // Parallel compilation limit
425
cache: boolean | object; // Webpack caching options
426
sourceMap: boolean | string; // Source map generation
427
minimize: boolean; // Code minification
428
}
429
```
430
431
**Usage Examples:**
432
433
```javascript
434
// webpack.config.js - Performance optimizations
435
const slsw = require('serverless-webpack');
436
437
module.exports = {
438
entry: slsw.lib.entries,
439
target: 'node',
440
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
441
442
// Faster builds in development
443
devtool: slsw.lib.webpack.isLocal ? 'eval-source-map' : 'source-map',
444
445
// Webpack 5 caching
446
cache: {
447
type: 'filesystem',
448
buildDependencies: {
449
config: [__filename]
450
}
451
},
452
453
optimization: {
454
minimize: !slsw.lib.webpack.isLocal,
455
splitChunks: slsw.lib.webpack.isLocal ? false : {
456
chunks: 'all',
457
cacheGroups: {
458
vendor: {
459
test: /[\\/]node_modules[\\/]/,
460
name: 'vendors',
461
chunks: 'all'
462
}
463
}
464
}
465
}
466
};
467
```
468
469
```yaml
470
# serverless.yml - Build performance settings
471
custom:
472
webpack:
473
concurrency: 2 # Limit for memory-constrained environments
474
keepOutputDirectory: true # Enable for debugging
475
```