Gathering detailed insights and metrics for serverless-webpack
Gathering detailed insights and metrics for serverless-webpack
Gathering detailed insights and metrics for serverless-webpack
Gathering detailed insights and metrics for serverless-webpack
serverless-bundle
An extension of the serverless-webpack plugin that bundles your ES6 + TypeScript Node.js Lambda functions.
serverless-webpack-prisma
When using serverless webpack, you can save up to 50% of package capacity by deleting unnecessary Prisma engine.
serverless-webpack-plugin
Serverless Webpack Plugin - Significantly reduces Lambda file size and improves performance
@chainfi/serverless-webpack-prisma
When using serverless webpack, you can save up to 50% of package capacity by deleting unnecessary Prisma engine.
Serverless plugin to bundle your lambdas with Webpack
npm install serverless-webpack
58.3
Supply Chain
71.5
Quality
79.2
Maintenance
100
Vulnerability
97.3
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,724 Stars
2,631 Commits
417 Forks
31 Watching
2 Branches
103 Contributors
Updated on 27 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-7.2%
49,070
Compared to previous day
Last week
2.2%
245,814
Compared to previous week
Last month
15.4%
1,023,689
Compared to previous month
Last year
-13.6%
12,053,145
Compared to previous year
3
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!
serverless package
, serverless deploy
and serverless deploy function
serverless invoke local
and serverless invoke local --watch
serverless run
and serverless run --watch
serverless-offline
to simulate local API Gateway endpointsFor the complete release notes see the end of this document.
1$ npm install serverless-webpack --save-dev
or
1$ yarn add serverless-webpack --dev
Add the plugin to your serverless.yml
file:
1plugins: 2 - serverless-webpack
If you are using Serverless v4 you must disable the default builtin ESBuild support in your serverless.yml
(because it conflicts with serverless-webpack
):
1build: 2 esbuild: false
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:
1custom: 2 webpack: 3 webpackConfig: 'webpack.config.js' # Name of webpack configuration file 4 includeModules: false # Node modules configuration for packaging 5 packager: 'npm' # Packager that will be used to package your external modules 6 excludeFiles: src/**/*.test.js # Provide a glob for files to ignore
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
.
1custom: 2 webpack: 3 webpackConfig: ./folder/my-webpack.config.js
A base Webpack configuration might look like this:
1// webpack.config.js 2 3module.exports = { 4 entry: './handler.js', 5 target: 'node', 6 module: { 7 loaders: [ ... ] 8 } 9};
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:
1// Version if the local Node.js version supports async/await 2// webpack.config.js 3 4const webpack = require('webpack') 5const slsw = require('serverless-webpack'); 6 7module.exports = (async () => { 8 const accountId = await slsw.lib.serverless.providers.aws.getAccountId(); 9 return { 10 entry: './handler.js', 11 target: 'node', 12 plugins: [ 13 new webpack.DefinePlugin({ 14 AWS_ACCOUNT_ID: `${accountId}`, 15 }), 16 ], 17 module: { 18 loaders: [ ... ] 19 } 20 }; 21})();
1// Version with promises 2// webpack.config.js 3 4const webpack = require('webpack') 5const slsw = require('serverless-webpack'); 6const BbPromise = require('bluebird'); 7 8module.exports = BbPromise.try(() => { 9 return slsw.lib.serverless.providers.aws.getAccountId() 10 .then(accountId => ({ 11 entry: './handler.js', 12 target: 'node', 13 plugins: [ 14 new webpack.DefinePlugin({ 15 AWS_ACCOUNT_ID: `${accountId}`, 16 }), 17 ], 18 module: { 19 loaders: [ ... ] 20 } 21 })); 22});
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.
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:
1// webpack.config.js 2const slsw = require('serverless-webpack'); 3 4module.exports = { 5 ... 6 entry: slsw.lib.entries, 7 ... 8};
Custom entries that are not part of the SLS build process can be added too:
1// webpack.config.js 2const _ = require('lodash'); 3const slsw = require('serverless-webpack'); 4 5module.exports = { 6 ... 7 entry: _.assign({ 8 myCustomEntry1: './custom/path/something.js' 9 }, slsw.lib.entries), 10 ... 11};
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
.
1functions: 2 my-function: 3 layers: 4 - LAYER-ARN 5 handler: layer.handler 6 entrypoint: src/index.handler
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.
lib.webpack
contains state variables that can be used to configure the build
dynamically on a specific plugin state.
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"
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:
1// webpack.config.js 2const path = require('path'); 3 4module.exports = { 5 // ... 6 output: { 7 libraryTarget: 'commonjs', 8 path: path.resolve(__dirname, '.webpack'), 9 filename: '[name].js' 10 } 11 // ... 12};
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
1// webpack.config.js 2 3module.exports = { 4 // ... 5 stats: 'minimal' 6 // ... 7};
All the stats config can be found in webpack's documentation
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
:
1// webpack.config.js 2var nodeExternals = require('webpack-node-externals'); 3 4module.exports = { 5 // we use webpack-node-externals to excludes all node deps. 6 // You can manually set the externals too. 7 externals: [nodeExternals()] 8};
1# serverless.yml 2custom: 3 webpack: 4 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
:
1# serverless.yml 2custom: 3 webpack: 4 includeModules: 5 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.
1# serverless.yml 2custom: 3 webpack: 4 includeModules: 5 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
:
1# serverless.yml 2custom: 3 webpack: 4 includeModules: 5 nodeModulesRelativeDir: '../../' # relative path to current working directory. 6 packagerOptions: 7 lockFile: '../../package-lock.json' # relative path to package-lock.json
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.
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).
1# serverless.yml 2custom: 3 webpack: 4 includeModules: 5 forceExclude: 6 - aws-sdk
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.
1# serverless.yml 2custom: 3 webpack: 4 packager: 'yarn' # Defaults to npm 5 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.
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.
If you need to generate ESM output, and you cannot safely produce a .mjs
file
(e.g. because that breaks serverless-offline),
you can use copyPackageSectionNames
to ensure the output package.json
defaults to ESM.
1custom: 2 webpack: 3 packagerOptions: 4 copyPackageSectionNames: 5 - type 6 - exports 7 - main
Using yarn will switch the whole packaging pipeline to use yarn, so does it use a yarn.lock
file.
The yarn 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 yarn install (assume install completed) |
noNonInteractive | bool | false | Disable interactive mode when using Yarn 2 or above |
noFrozenLockfile | bool | false | Do not require an up-to-date yarn.lock |
networkConcurrency | int | Specify number of concurrent network requests | |
copyPackageSectionNames | string[] | ['resolutions'] | Entries in your package.json to copy to the output package.json |
There are some settings that are common to all packagers and affect the packaging itself.
You can specify custom scripts that are executed after the installation of the function/service packages
has been finished. These are standard packager scripts as they can be used in any package.json
.
Warning: The use cases for them are very rare and specific and you should investigate first,
if your use case can be covered with webpack plugins first. They should never access files
outside of their current working directory which is the compiled function folder, if any.
A valid use case would be to start anything available as binary from node_modules
.
1custom: 2 webpack: 3 packagerOptions: 4 scripts: 5 - npm rebuild grpc --target=6.1.0 --target_arch=x64 --target_platform=linux --target_libc=glibc
Sometimes it might happen that you use dynamic requires in your code, i.e. you
require modules that are only known at runtime. Webpack is not able to detect
such externals and the compiled package will miss the needed dependencies.
In such cases you can force the plugin to include certain modules by setting
them in the forceInclude
array property. However the module must appear in
your service's production dependencies in package.json
.
1# serverless.yml 2custom: 3 webpack: 4 includeModules: 5 forceInclude: 6 - module1 7 - module2
You can forcefully exclude detected external modules, e.g. if you have a module in your dependencies that is already installed at your provider's environment.
Just add them to the forceExclude
array property and they will not be packaged.
1# serverless.yml 2custom: 3 webpack: 4 includeModules: 5 forceExclude: 6 - module1 7 - module2
If you specify a module in both arrays, forceInclude
and forceExclude
, the
exclude wins and the module will not be packaged.
You can use file:
version references in your package.json
to use a node module
from a local folder (e.g. "mymodule": "file:../../myOtherProject/mymodule"
).
With that you can do test deployments from the local machine with different
module versions or modules before they are published officially.
If you have a project structure that uses something like index.js
and a
co-located index.test.js
then you have likely seen an error like:
WARNING: More than one matching handlers found for index. Using index.js
This config option allows you to exclude files that match a glob from function
resolution. Just add: excludeFiles: **/*.test.js
(with whatever glob you want
to exclude).
1# serverless.yml 2custom: 3 webpack: 4 excludeFiles: **/*.test.js
This is also useful for projects that use TypeScript.
This config option allows you to filter files that match a regex pattern before
adding to the zip file. Just add: excludeRegex: \.ts|test|\.map
(with whatever
regex you want to exclude).
1# serverless.yml 2custom: 3 webpack: 4 excludeRegex: \.ts|test|\.map
You can keep the output directory (defaults to .webpack
) from being removed
after build.
Just add keepOutputDirectory: true
1# serverless.yml 2custom: 3 webpack: 4 keepOutputDirectory: true
This can be useful, in case you want to upload the source maps to your Error reporting system, or just have it available for some post processing.
If you are using a nodejs custom runtime you can add the property allowCustomRuntime: true
.
1exampleFunction: 2 handler: path/to/your/handler.default 3 runtime: provided 4 allowCustomRuntime: true
⚠️ Note: this will only work if your custom runtime and function are written in JavaScript.
Make sure you know what you are doing when this option is set to true
You can find an example setups in the examples
folder.
If you do not enable individual packaging in your service (serverless.yml), the plugin creates one ZIP file for all functions (the service package) that includes all node modules used in the service. This is the fastest packaging, but not the optimal one, as node modules are always packaged, that are not needed by some functions.
A better way to do the packaging, is to enable individual packaging in your service:
1# serverless.yml 2--- 3package: 4 individually: true
This will switch the plugin to per function packaging which makes use of the multi-compiler feature of Webpack. That means, that Webpack compiles and optimizes each function individually, removing unnecessary imports and reducing code sizes significantly. Tree-Shaking only makes sense with this approach.
Now the needed external node modules are also detected by Webpack per function and the plugin only packages the needed ones into the function artifacts. As a result, the deployed artifacts are smaller, depending on the functions and cold-start times (to install the functions into the cloud at runtime) are reduced too.
The individual packaging will automatically apply the automatic entry resolution (see above) and you will not be able to configure the entry config in webpack. An error will be thrown if you are trying to override the entry in webpack.config.js with other unsupported values.
The individual packaging needs more time at the packaging phase, but you'll get that paid back twice at runtime.
1# serverless.yml 2custom: 3 webpack: 4 concurrency: 5 # desired concurrency, defaults to the number of available cores 5 serializedCompile: true # backward compatible, this translates to concurrency: 1
Will run each webpack build one at a time which helps reduce memory usage and in some cases impoves overall build performance.
AWS Lambda and serverless
started supporting the use of Docker images as custom runtimes in 2021. See the serverless documentation for details on how to configure a serverless.yml
to use these features.
NOTE: You must provide an override for the Image CMD
property in your function definitions.
See Dockerfile documentation for more information about the native Docker CMD
property.
In the following example entrypoint
is inherited from the shared Docker image, while command
is provided as an override for each function:
1# serverless.yml 2functions: 3 myFunction1: 4 image: 5 name: public.ecr.aws/lambda/nodejs:12 6 command: 7 - app.handler1 8 myFunction2: 9 image: 10 name: public.ecr.aws/lambda/nodejs:12 11 command: 12 - app.handler2
If you want to use a remote docker image but still need the webpack process before doing so, you can specify it as indicated below:
1# serverless.yml 2functions: 3 myFunction1: 4 image: public.ecr.aws/lambda/nodejs:latest
The normal Serverless deploy procedure will automatically bundle with Webpack:
serverless create -t aws-nodejs
serverless deploy
The plugin fully integrates with serverless invoke local
. To run your bundled functions
locally you can:
1$ serverless invoke local --function <function-name>
All options that are supported by invoke local can be used as usual:
--function
or -f
(required) is the name of the function to run--path
or -p
(optional) is a JSON file path used as the function input event--data
or -d
(optional) inline JSON data used as the function input event:exclamation: The old
webpack invoke
command has been disabled.
On CI systems it is likely that you'll run multiple integration tests with invoke local
sequentially. To improve this, you can do one compile and run multiple invokes on the
compiled output - it is not necessary to compile again before each and every invoke.
--skip-build
1$ serverless webpack 2$ serverless invoke local --function <function-name-1> --skip-build 3$ serverless invoke local --function <function-name-2> --skip-build
noBuild
1custom: 2 webpack: 3 noBuild: true
Or to run a function every time the source files change use the --watch
option
together with serverless invoke local
:
1$ serverless invoke local --function <function-name> --path event.json --watch
Everytime the sources are changed, the function will be executed again with the changed sources. The command will watch until the process is terminated.
If you have your sources located on a file system that does not offer events,
you can enable polling with the --webpack-use-polling=<time in ms>
option.
If you omit the value, it defaults to 3000 ms.
All options that are supported by invoke local can be used as usual:
--function
or -f
(required) is the name of the function to run--path
or -p
(optional) is a JSON file path used as the function input event--data
or -d
(optional) inline JSON data used as the function input event:exclamation: The old
webpack watch
command has been disabled.
The serverless run
command is supported with the plugin. To test a local
service with the Serverless Emulator, you can use the serverless run
command as documented by Serverless. The command will compile the code before
it uploads it into the event gateway.
You can enable source watch mode with serverless run --watch
. The plugin will
then watch for any source changes, recompile and redeploy the code to the event
gateway. So you can just keep the event gateway running and test new code immediately.
The plugin integrates very well with serverless-offline to simulate AWS Lambda and AWS API Gateway locally.
Add the plugins to your serverless.yml
file and make sure that serverless-webpack
precedes serverless-offline
as the order is important:
1plugins: ... 2 - serverless-webpack 3 ... 4 - serverless-offline 5 ...
Run serverless offline
or serverless offline start
to start the Lambda/API simulation.
In comparison to serverless offline
, the start
command will fire an init
and a end
lifecycle hook which is needed for serverless-offline
and e.g. serverless-dynamodb-local
to switch off resources (see below).
You can find an example setup in the examples
folder.
By default the plugin starts in watch mode when triggered through serverless offline
, i.e.
it automatically recompiles your code if it detects a change in the used sources.
After a change it might take some seconds until the emulated endpoints are updated.
If you have your sources located on a file system that does not offer events,
e.g. a mounted volume in a Docker container, you can enable polling with the
--webpack-use-polling=<time in ms>
option. If you omit the value, it defaults
to 3000 ms.
If you don't want the plugin to build when using serverless-offline
, select the --skip-build
option.
If you do not use the default path and override it in your Webpack configuration,
you have use the --location
option.
Configure your service the same as mentioned above, but additionally add the serverless-dynamodb-local
plugin as follows:
1plugins: 2 - serverless-webpack 3 - serverless-dynamodb-local 4 - serverless-offline
Run serverless offline start
.
You can disable timeouts with --noTimeout
when using serverless-offline
.
If you use serverless offline to run your integration tests, you might want to
disable the automatic watch mode with the --webpack-no-watch
switch.
To just bundle and see the output result use:
1$ serverless webpack --out dist
Options are:
--out
or -o
(optional) The output directory. Defaults to .webpack
.:exclamation: The serve command has been removed. See above how to achieve the
same functionality with the serverless-offline
plugin.
To debug your functions using serverless invoke local
or serverless-offline
check this .vscode/launch.json example
.
In the examples
folder there is a Serverless project using this
plugin with Babel. To try it, from inside the example folder:
npm install
to install dependenciesserverless invoke local -f hello
to run the example functionPlugin commands are supported by the following providers. ⁇ indicates that command has not been tested with that provider.
AWS Lambda | Apache OpenWhisk | Azure Functions | Google Cloud Functions | |
---|---|---|---|---|
webpack | ✔︎ | ✔︎ | ⁇ | ⁇ |
invoke local | ✔︎ | ✔︎ | ⁇ | ⁇ |
invoke local --watch | ✔︎ | ✔︎ | ⁇ | ⁇ |
The following serverless plugins are explicitly supported with serverless-webpack
Plugin | NPM |
---|---|
serverless-offline | |
serverless-step-functions-offline |
The plugin exposes a complete lifecycle model that can be hooked by other plugins to extend the functionality of the plugin or add additional actions.
All events (H) can be hooked by a plugin.
-> webpack:validate
-> webpack:validate:validate (H)
-> webpack:compile
-> webpack:compile:compile (H)
-> webpack:compile:watch:compile (H)
-> webpack:package
-> webpack:package:packExternalModules (H)
-> webpack:package:packageModules (H)
The following list shows all lifecycles that are invoked/started by the plugin when running a command or invoked by a hook.
-> before:package:createDeploymentArtifacts
-> webpack:validate
-> webpack:compile
-> webpack:package
-> before:deploy:function:packageFunction
-> webpack:validate
-> webpack:compile
-> webpack:package
-> before:invoke:local:invoke
-> webpack:validate
-> webpack:compile
-> webpack
-> webpack:validate
-> webpack:compile
-> webpack:package
-> before:offline:start
-> webpack:validate
-> webpack:compile
-> before:offline:start:init
-> webpack:validate
-> webpack:compile
Special thanks go to the initial author of serverless-webpack, Nicola Peduzzi, who allowed me to take it over and continue working on the project. That helped to revive it and lead it to new horizons.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
30 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More