Serverless Webpack
A Serverless Framework plugin to build your lambda functions with Webpack.
This plugin is for you if you want to use the latest Javascript version with Babel;
use custom resource loaders, optimize your packaged functions individually
and much more!
Highlights
- Configuration possibilities range from zero-config to fully customizable
- Support of
serverless package, serverless deploy and serverless deploy function
- Support of
serverless invoke local and serverless invoke local --watch
- Support of
serverless run and serverless run --watch
- Integrates with
serverless-offline to simulate local API Gateway endpoints
- When enabled in your service configuration, functions are packaged and compiled
individually, resulting in smaller Lambda packages that contain only the code and
dependencies needed to run the function. This allows the plugin to fully utilize
WebPack's Tree-Shaking optimization.
- Webpack version 3, 4 and 5 support
- Support NPM and Yarn for packaging
- Support asynchronous webpack configuration
For the complete release notes see the end of this document.
Install
$ npm install serverless-webpack --save-dev
or
$ yarn add serverless-webpack --dev
Add the plugin to your serverless.yml file:
plugins:
- serverless-webpack
Node.js requirement
serverless-webpack now requires Node.js >= 20.
Serverless v4 requirement
If you are using Serverless v4 you must disable the default builtin ESBuild support in your serverless.yml (because it conflicts with serverless-webpack):
build:
esbuild: false
Configure
The configuration of the plugin is done by defining a custom: webpack object in your serverless.yml with your specific configuration. All settings are optional and will be set to reasonable defaults if missing.
See the sections below for detailed descriptions of the settings. The defaults are:
custom:
webpack:
webpackConfig: 'webpack.config.js' # Name of webpack configuration file
includeModules: false # Node modules configuration for packaging
packager: 'npm' # Packager that will be used to package your external modules
excludeFiles: src/**/*.test.js # Provide a glob for files to ignore
Webpack configuration file
By default the plugin will look for a webpack.config.js in the service directory. Alternatively, you can specify a different file or configuration in serverless.yml.
custom:
webpack:
webpackConfig: ./folder/my-webpack.config.js
A base Webpack configuration might look like this:
// webpack.config.js
module.exports = {
entry: './handler.js',
target: 'node',
module: {
loaders: [ ... ]
}
};
Alternatively the Webpack configuration can export an asynchronous object (e.g. a promise or async function) which will be awaited by the plugin and resolves to the final configuration object. This is useful if the confguration depends on asynchronous functions, for example, defining the AccountId of the current aws user inside AWS lambda@edge which does not support defining normal process environment variables.
A basic Webpack promise configuration might look like this:
// webpack.config.js
const webpack = require('webpack')
const slsw = require('serverless-webpack');
module.exports = (async () => {
const accountId = await slsw.lib.serverless.providers.aws.getAccountId();
return {
entry: './handler.js',
target: 'node',
plugins: [
new webpack.DefinePlugin({
AWS_ACCOUNT_ID: `${accountId}`,
}),
],
module: {
loaders: [ ... ]
}
};
})();
// Version with native promises
// webpack.config.js
const webpack = require('webpack')
const slsw = require('serverless-webpack');
module.exports = Promise.resolve()
.then(() => slsw.lib.serverless.providers.aws.getAccountId())
.then(accountId => ({
entry: './handler.js',
target: 'node',
plugins: [
new webpack.DefinePlugin({
AWS_ACCOUNT_ID: `${accountId}`,
}),
],
module: {
loaders: [ ... ]
}
}));
serverless-webpack lib export helper
serverless-webpack exposes a lib object, that can be used in your webpack.config.js
to make the configuration easier and to build fully dynamic configurations.
This is the preferred way to configure webpack - the plugin will take care of
as much of the configuration (and subsequent changes in your services) as it can.
Automatic entry resolution
You can let the plugin determine the correct handler entry points at build time.
Then you do not have to care anymore when you add or remove functions from your service:
// webpack.config.js
const slsw = require('serverless-webpack');
module.exports = {
...
entry: slsw.lib.entries,
...
};
Custom entries that are not part of the SLS build process can be added too:
// webpack.config.js
const _ = require('lodash');
const slsw = require('serverless-webpack');
module.exports = {
...
entry: _.assign({
myCustomEntry1: './custom/path/something.js'
}, slsw.lib.entries),
...
};
Optional entry overrides
serverless-webpack generates Webpack entries from the handler value by default.
If your handler is different from the webpack entry, e.g. provided by a layer,
you may override the generated entry at function level via the entrypoint
option in serverless.yml.
functions:
my-function:
layers:
- LAYER-ARN
handler: layer.handler
entrypoint: src/index.handler
Full customization (for experts)
The lib export also provides the serverless and options properties, through
which you can access the Serverless instance and the options given on the command-line.
The current stage e.g is accessible through slsw.lib.options.stage
This enables you to have a fully customized dynamic configuration, that can evaluate
anything available in the Serverless framework. There are really no limits.
Samples are: The current stage and the complete service definition. You thereby
have access to anything that a Serverless plugin would have access to.
Both properties should be handled with care and should never be written to,
as that will modify the running framework and leads to unpredictable behavior!
If you have cool use cases with the full customization, we might add your solution
to the plugin examples as showcase.
Invocation state
lib.webpack contains state variables that can be used to configure the build
dynamically on a specific plugin state.
isLocal
lib.webpack.isLocal is a boolean property that is set to true, if any known
mechanism is used in the current Serverless invocation that runs code locally.
This allows to set properties in the webpack configuration differently depending
if the lambda code is run on the local machine or deployed.
A sample is to set the compile mode with Webpack 4:
mode: slsw.lib.webpack.isLocal ? "development" : "production"
Output
Note that, if the output configuration is not set, it will automatically be
generated to write bundles in the .webpack directory. If you set your own output
configuration make sure to add a libraryTarget
for best compatibility with external dependencies:
// webpack.config.js
const path = require('path');
module.exports = {
// ...
output: {
libraryTarget: 'commonjs',
path: path.resolve(__dirname, '.webpack'),
filename: '[name].js'
}
// ...
};
Stats
By default, the plugin will print a quite verbose bundle information to your console. However, if
you are not satisfied with the current output info, you can overwrite it in your webpack.config.js
// webpack.config.js
module.exports = {
// ...
stats: 'minimal'
// ...
};
All the stats config can be found in webpack's documentation
Node modules / externals
By default, the plugin will try to bundle all dependencies. However, you don't
want to include all modules in some cases such as selectively import, excluding
builtin package (ie: aws-sdk) and handling webpack-incompatible modules.
In this case you might add external modules in
Webpack's externals configuration.
Those modules can be included in the Serverless bundle with the custom: webpack: includeModules
option in serverless.yml:
// webpack.config.js
var nodeExternals = require('webpack-node-externals');
module.exports = {
// we use webpack-node-externals to excludes all node deps.
// You can manually set the externals too.
externals: [nodeExternals()]
};
# serverless.yml
custom:
webpack:
includeModules: true # enable auto-packing of external modules
All modules stated in externals will be excluded from bundled files. If an excluded module
is stated as dependencies in package.json and it is used by the webpack chunk, it will be
packed into the Serverless artifact under the node_modules directory.
By default, the plugin will use the package.json file in working directory, If you want to
use a different package file, set packagePath to your custom package.json:
# serverless.yml
custom:
webpack:
includeModules:
packagePath: '../package.json' # relative path to custom package.json file.
Note that only relative path is supported at the moment.
peerDependencies of all above external dependencies will also be packed into the Serverless
artifact. By default, node_modules in the same directory as package.json (current working directory
or specified bypackagePath) will be used.
However in some configuration (like monorepo), node_modules is in parent directory which is different from
where package.json is. Set nodeModulesRelativeDir to specify the relative directory where node_modules is.
# serverless.yml
custom:
webpack:
includeModules:
nodeModulesRelativeDir: '../../' # relative path to current working directory.
When using NPM 8, peerDependencies are automatically installed by default. In order to avoid adding all transitive dependencies to your package.json, we will use the package-lock.json when possible. If your project is included in a monorepo, you can specify the path to the package-lock.json:
# serverless.yml
custom:
webpack:
includeModules:
nodeModulesRelativeDir: '../../' # relative path to current working directory.
packagerOptions:
lockFile: '../../package-lock.json' # relative path to package-lock.json
Runtime dependencies
If a runtime dependency is detected that is found in the devDependencies section and
so would not be packaged, the plugin will error until you explicitly exclude it (see forceExclude below)
or move it to the dependencies section.
AWS-SDK
An exception for the runtime dependency error is the AWS-SDK. All projects using the AWS-SDK normally
have it listed in devDependencies because AWS provides it already in their Lambda environment. In this case
the aws-sdk is automatically excluded and only an informational message is printed (in --verbose mode).
The main reason for the warning is, that silently ignoring anything contradicts the declarative nature
of Serverless' service definition. So the correct way to define the handling for the aws-sdk is, as
you would do for all other excluded modules (see forceExclude below).
# serverless.yml
custom:
webpack:
includeModules:
forceExclude:
- aws-sdk
Packagers
You can select the packager that will be used to package your external modules.
The packager can be set with the packager configuration. Currently it can be 'npm'
or 'yarn' and defaults to using npm when not set.
# serverless.yml
custom:
webpack:
packager: 'yarn' # Defaults to npm
packagerOptions: {} # Optional, depending on the selected packager
You should select the packager, that you use to develop your projects, because only
then locked versions will be handled correctly, i.e. the plugin uses the generated
(and usually committed) package lock file that is created by your favorite packager.
Each packager might support specific options that can be set in the packagerOptions
configuration setting. For details see below.
NPM
By default, the plugin uses NPM to package the external modules. However, if you use npm,
you should use any version <5.5 >=5.7.1 as the versions in-between have some nasty bugs.
The NPM packager supports the following packagerOptions:
| Option |
Type |
Default |
Description |
| ignoreScripts |
bool |
false |
Do not execute package.json hook scripts on install |
| noInstall |
bool |
false |
Do not run npm install (assume install completed) |
| lockFile |
string |
./package-lock.json |
Relative path to lock file to use |
| copyPackageSectionNames |
string[] |
[] |
Entries in your package.json to copy to the output package.json (ie: ESM output) |
When using NPM version >= 7.0.0, we will use the package-lock.json file instead of modules installed in node_modules. This improves the
supports of NPM >= 8.0.0 which installs peer-dependencies automatically. The plugin will be able to detect the correct version.
ESM output