0
# Webpack Integration
1
2
The `lib` export provides webpack configurations with access to Serverless context, auto-generated entries, and build state information.
3
4
## Capabilities
5
6
### Lib Export Access
7
8
Import and use the serverless-webpack lib export in your webpack configuration.
9
10
```javascript { .api }
11
const slsw = require('serverless-webpack');
12
13
// Available lib properties (extended at runtime by plugin)
14
slsw.lib.entries: { [functionName: string]: string }; // Auto-generated webpack entries from functions
15
slsw.lib.webpack: { isLocal: boolean }; // Build context and state information
16
slsw.lib.serverless: ServerlessInstance; // Full Serverless framework instance access
17
slsw.lib.options: { [key: string]: string | boolean | number } & { param?: string[] }; // Command-line options and parameters
18
```
19
20
**Runtime Extension:** The lib export starts as a basic object but is extended at runtime by the plugin with `serverless`, `options`, and `entries` properties during the validation phase.
21
22
**Usage Examples:**
23
24
```javascript
25
// Basic usage with auto-generated entries
26
const slsw = require('serverless-webpack');
27
28
module.exports = {
29
entry: slsw.lib.entries,
30
target: 'node',
31
mode: slsw.lib.webpack.isLocal ? 'development' : 'production'
32
};
33
34
// Access command-line options
35
const slsw = require('serverless-webpack');
36
37
module.exports = {
38
entry: slsw.lib.entries,
39
target: 'node',
40
devtool: slsw.lib.options.stage === 'dev' ? 'source-map' : false
41
};
42
```
43
44
### Auto-Generated Entries
45
46
Automatically resolve webpack entry points from Serverless function definitions.
47
48
```javascript { .api }
49
/**
50
* Auto-generated webpack entries object mapping function names to handler file paths
51
*/
52
slsw.lib.entries: { [functionName: string]: string };
53
```
54
55
The entries object is automatically populated based on your serverless.yml function definitions:
56
57
**Usage Examples:**
58
59
```javascript
60
// Use auto-generated entries
61
const slsw = require('serverless-webpack');
62
63
module.exports = {
64
entry: slsw.lib.entries, // Automatically includes all function handlers
65
target: 'node'
66
};
67
68
// Combine with custom entries
69
const _ = require('lodash');
70
const slsw = require('serverless-webpack');
71
72
module.exports = {
73
entry: _.assign({
74
customEntry: './src/custom-handler.js',
75
utilityEntry: './src/utilities.js'
76
}, slsw.lib.entries),
77
target: 'node'
78
};
79
```
80
81
For a serverless.yml with functions:
82
```yaml
83
functions:
84
hello:
85
handler: src/handlers/hello.handler
86
goodbye:
87
handler: src/handlers/goodbye.handler
88
```
89
90
The `slsw.lib.entries` object becomes:
91
```javascript
92
{
93
hello: './src/handlers/hello.js',
94
goodbye: './src/handlers/goodbye.js'
95
}
96
```
97
98
### Build Context State
99
100
Access build context and environment information through the webpack state object.
101
102
```javascript { .api }
103
/**
104
* Webpack build context and state information
105
*/
106
slsw.lib.webpack: {
107
isLocal: boolean; // True when running locally (invoke local, offline, run commands)
108
}
109
```
110
111
**Usage Examples:**
112
113
```javascript
114
const slsw = require('serverless-webpack');
115
116
module.exports = {
117
entry: slsw.lib.entries,
118
target: 'node',
119
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
120
devtool: slsw.lib.webpack.isLocal ? 'eval-source-map' : false,
121
optimization: {
122
minimize: !slsw.lib.webpack.isLocal
123
}
124
};
125
```
126
127
### Serverless Framework Access
128
129
Access the full Serverless framework instance for advanced webpack configuration.
130
131
```javascript { .api }
132
/**
133
* Full Serverless framework instance providing access to service configuration,
134
* providers, plugins, and all framework capabilities
135
*/
136
slsw.lib.serverless: ServerlessInstance;
137
```
138
139
**Usage Examples:**
140
141
```javascript
142
const slsw = require('serverless-webpack');
143
const webpack = require('webpack');
144
145
module.exports = async () => {
146
// Access AWS provider for dynamic configuration
147
const accountId = await slsw.lib.serverless.providers.aws.getAccountId();
148
const region = slsw.lib.serverless.providers.aws.getRegion();
149
150
return {
151
entry: slsw.lib.entries,
152
target: 'node',
153
plugins: [
154
new webpack.DefinePlugin({
155
AWS_ACCOUNT_ID: JSON.stringify(accountId),
156
AWS_REGION: JSON.stringify(region),
157
SERVICE_NAME: JSON.stringify(slsw.lib.serverless.service.service)
158
})
159
]
160
};
161
};
162
163
// Access service configuration
164
const slsw = require('serverless-webpack');
165
166
module.exports = {
167
entry: slsw.lib.entries,
168
target: 'node',
169
externals: slsw.lib.serverless.service.provider.name === 'aws'
170
? ['aws-sdk']
171
: []
172
};
173
```
174
175
### Command-Line Options
176
177
Access command-line options and parameters passed to Serverless commands.
178
179
```javascript { .api }
180
/**
181
* Command-line options and parameters object
182
*/
183
slsw.lib.options: {
184
[key: string]: string | boolean | number;
185
stage?: string; // Deployment stage
186
region?: string; // AWS region
187
function?: string; // Specific function name
188
param?: string[]; // Additional parameters array
189
}
190
```
191
192
**Usage Examples:**
193
194
```javascript
195
const slsw = require('serverless-webpack');
196
197
module.exports = {
198
entry: slsw.lib.entries,
199
target: 'node',
200
// Different optimization based on stage
201
optimization: {
202
minimize: slsw.lib.options.stage === 'prod',
203
splitChunks: slsw.lib.options.stage === 'prod' ? {
204
chunks: 'all'
205
} : false
206
},
207
// Environment-specific externals
208
externals: slsw.lib.options.stage === 'local' ? [] : ['aws-sdk']
209
};
210
```
211
212
### Asynchronous Webpack Configuration
213
214
Support for asynchronous webpack configurations using async/await or Promises.
215
216
```javascript { .api }
217
/**
218
* Webpack configuration can be:
219
* - Synchronous object
220
* - Async function returning configuration object
221
* - Promise resolving to configuration object
222
*/
223
module.exports: object | (() => Promise<object>) | Promise<object>;
224
```
225
226
**Usage Examples:**
227
228
```javascript
229
// Async function approach
230
const slsw = require('serverless-webpack');
231
232
module.exports = async () => {
233
const accountId = await slsw.lib.serverless.providers.aws.getAccountId();
234
235
return {
236
entry: slsw.lib.entries,
237
target: 'node',
238
plugins: [
239
new webpack.DefinePlugin({
240
ACCOUNT_ID: JSON.stringify(accountId)
241
})
242
]
243
};
244
};
245
246
// Promise approach
247
const slsw = require('serverless-webpack');
248
const BbPromise = require('bluebird');
249
250
module.exports = BbPromise.try(() => {
251
return slsw.lib.serverless.providers.aws.getAccountId()
252
.then(accountId => ({
253
entry: slsw.lib.entries,
254
target: 'node',
255
plugins: [
256
new webpack.DefinePlugin({
257
ACCOUNT_ID: JSON.stringify(accountId)
258
})
259
]
260
}));
261
});
262
```
263
264
### Function Entry Overrides
265
266
Override auto-generated entries for specific functions using the `entrypoint` option.
267
268
```yaml { .api }
269
# In serverless.yml - override entry for functions with custom entrypoints
270
functions:
271
my-function:
272
handler: layer.handler # Handler from layer
273
entrypoint: src/index.handler # Actual webpack entry point
274
layers:
275
- LAYER-ARN
276
```
277
278
This allows webpack to use `src/index.handler` as the entry point while the actual Lambda handler remains `layer.handler`.
279
280
### TypeScript Support Integration
281
282
Automatic TypeScript compilation support when using .ts webpack configurations.
283
284
```javascript { .api }
285
// Automatically detected TypeScript webpack config support
286
// webpack.config.ts or custom.webpack.webpackConfig ending in .ts
287
// Requires ts-node as dependency for compilation
288
```
289
290
**Usage Examples:**
291
292
```yaml
293
# serverless.yml with TypeScript webpack config
294
custom:
295
webpack:
296
webpackConfig: 'webpack.config.ts'
297
```
298
299
```typescript
300
// webpack.config.ts
301
import { Configuration } from 'webpack';
302
const slsw = require('serverless-webpack');
303
304
const config: Configuration = {
305
entry: slsw.lib.entries,
306
target: 'node',
307
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
308
module: {
309
rules: [
310
{
311
test: /\.ts$/,
312
use: 'ts-loader',
313
exclude: /node_modules/
314
}
315
]
316
},
317
resolve: {
318
extensions: ['.ts', '.js']
319
}
320
};
321
322
export = config;
323
```
324
325
## Integration Patterns
326
327
### Zero-Config Setup
328
329
Use serverless-webpack with minimal configuration for standard projects.
330
331
```javascript
332
// webpack.config.js - minimal setup
333
const slsw = require('serverless-webpack');
334
335
module.exports = {
336
entry: slsw.lib.entries,
337
target: 'node'
338
};
339
```
340
341
### Advanced Dynamic Configuration
342
343
Leverage full Serverless context for complex, environment-aware webpack configurations.
344
345
```javascript
346
const slsw = require('serverless-webpack');
347
const path = require('path');
348
349
module.exports = async () => {
350
const service = slsw.lib.serverless.service;
351
const stage = slsw.lib.options.stage;
352
const isProduction = stage === 'production';
353
354
return {
355
entry: slsw.lib.entries,
356
target: 'node',
357
mode: isProduction ? 'production' : 'development',
358
output: {
359
libraryTarget: 'commonjs',
360
path: path.resolve(__dirname, '.webpack'),
361
filename: '[name].js'
362
},
363
optimization: {
364
minimize: isProduction
365
},
366
externals: service.provider.name === 'aws' ? ['aws-sdk'] : [],
367
resolve: {
368
alias: {
369
'@': path.resolve(__dirname, 'src')
370
}
371
}
372
};
373
};
374
```