Skip to content

Reduce the size and speed up your Node.js based lambda's using browserify.

License

Notifications You must be signed in to change notification settings

digitalmaas/serverless-plugin-browserifier

Repository files navigation

Serverless Browserifier Plugin

serverless NPM version digitalmaas NPM downloads standardjs

A Serverless plugin that uses browserify to bundle your Node.js Lambda functions. Works with serverless versions 1 to 3.

  1. Supported Commands
  2. Motivation
  3. Installation
  4. Basic Setup
  5. Advanced Configuration
  6. FAQ
  7. Useful Information
  8. License

Supported Commands

  • serverless package
  • serverless deploy
  • serverless deploy function
  • serverless invoke local
    • the plugin will automatically build and use your bundle to execute the function locally; to avoid it, you can use the --no-build option, which will then use your handler file directly

Motivation

Smaller Lambda functions that run faster, with minimal changes to normal serverless configuration.

Smaller and faster

A project usualy contains several dependencies that are required by different functions in miscellaneous combinations, and packaging it all up for every function generates very large and inefficient bundles. This plugin leverages browserify's ability of bundling up all files requested using require, generating a single lean file with all that is needed for each specific function.

Normal serverless packaging includes all files within the node_modules structures, including several files that are not really needed during runtime, like package.json files, documentation files, and much more. And although recent versions of serverless automatically ignore devDependencies, you'll certainly still have more dependencies than needed for each single function.

Serverless does support manual preparation of packages, but you will still have to take care of that for each single function individually, which can quickly get out of hand dependending on the number of dependencies you need. This is specially hard after npm v3, due to dependency tree flattening.

The reduction is package size is, on average, superior to 90%. This is important as AWS Lambda has an account-wide deployment package size limit, and reduces file transfer times.

Less code to parse also means quicker Lambda cold start.

Minimal changes

When using this plugin, one of the goals is to reduce serverless configuration changes as much as possible. It must possible to just remove it and resume normal usage of serverless, without any additional modifications.

No preset uglification, minification, nor transpilation; just plain bundling. You can add any other transformations you want by using common browserify plugins.

Installation

From your target serverless project, run:

npm install serverless-plugin-browserifier --save-dev

Basic Setup

Add the plugin to your serverless.yml:

plugins:
  - serverless-plugin-browserifier
package:
  individually: true

The package.individually setting must be set -- either on global or function level -- to allow minimal bundle size based on each lambda's entrypoint.

You're all set! Use your normal serverless commands to package and deploy.

Advanced Configuration

For most use cases you should NOT need to do any extra configuration. That said, the ability is present if you need it.

The base config for browserify is read from the custom.browserify section of serverless.yml. All browserify options are supported (most are auto configured by this plugin). This plugin adds one special option disable which if true will bypass this plugin.

The base config can be overridden on a function-by-function basis. Again, custom.browserify is not required and should not even need to be defined in most cases.

custom:
  browserify:
    # any option defined in https://github.com/substack/node-browserify#browserifyfiles--opts
    extensions:
      - .js # default

functions:
  usersGet:
    description: Get users
    handler: users/index.handler
    browserify:
      # any option defined in https://github.com/substack/node-browserify#browserifyfiles--opts
      noParse:
        - ./someBig.json  # browserify can't optimize json, will take long time to parse for nothing

If you find a package that is not supported or does not behave well with browserify, you can still use function level package.include to include extra modules and files to your package. That said, you are encouraged to verify if you specific case can be dealt with by leveraging all available browserify options in your serverless.yml custom browserify section.

You can still use serveless' package[include|exclude] options to include extra files within your bundles, if necessary.

Disabling

You can disable the plugin completely by setting the global or function level disable flag:

custom:
  browserify:
    disable: true

# ... or ...

functions:
  usersGet:
    handler: users/index.handler
    browserify:
      disable: true

Debugging

When this plugin is enabled, and package.individually is true, running serverless deploy and serverless deploy -f <funcName> will automatically browserify your Node.js lambda code.

If you want to see more information about the process, simply set envvar SLS_DEBUG=* for full serverless debug output, or SLS_BROWSERIFIER_DEBUG=* for plugin only debug messages. Example:

$ export SLS_BROWSERIFIER_DEBUG=*
$ sls deploy function -v -f usersGet

You may also verify your bundles by simply using sls package, which bundles everything up but does not deploy.

Using browserify plugins/transforms

If you want to use browserify plugins, you can easily do that by using the global browserify options. As the plugin merely passes that up to browserify, as if it is calling the main browserify function, you can use it to add any transformations you want.

Do you want to transpile using TypeScript? No problem! You can use tsify:

# if you have no transform package options
custom:
  browserify:
    transform:
      - tsify                    # single dash!

# if you have extra transform package options
custom:
  browserify:
    transform:
      - - tsify                  # array of array, two dashes!
        - noImplicitAny: true

# multiple mixed transforms
custom:
  browserify:
    transform:
      - jstify
      - - tsify
        - noImplicitAny: true

For an in-depth example, please check this issue.

Best practices

If using it with AWS, use discrete SDK clients!

The official aws-sdk-js officially supports browserify. That allows us to further reduce the size of our bundles (and Lambda memory usage and speed) by loading only what is strictly needed.

// instead of ...
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
// ... you should use ...
const S3 = require('aws-sdk/clients/s3')
const s3 = new S3()

Ignore AWS SDK v2!

Although you can use discrete clients (see item above), AWS Lambda service always bundles up the latest v2 SDK version in its Lambda container image. That means that, even if you don't add AWS SDK to your bundle, it will still be available in for your code in runtime.

Therefore, if you don't need any specific AWS SDK v2 version, you can add the following to your plugin config:

custom:
  browserify:
    exclude:
      - aws-sdk
      - aws-sdk/clients/s3

To help you out, here's a script you can use to hide aws-sdk and all its clients from browserify. You can use it in your custom config for the plugin in serverless.yml:

# serverless.yml

custom:
  browserify: ${file(./custom.browserify.js)}
// custom.browserify.js
//
const fs = require('fs')
const path = require('path')

module.exports = function browserifyOptions () {
  // may contain any option defined in
  // https://github.com/substack/node-browserify#browserifyfiles--opts
  return {
    noParse: ['/**/*.json'],
    exclude: ['aws-sdk', ...getAllAwsSdkClients()]
  }
}

function getAllAwsSdkClients () {
  return fs
    .readdirSync('./node_modules/aws-sdk/clients', { withFileTypes: true })
    .filter(file => file.isFile() && path.extname(file.name) === '.js')
    .map(file => `aws-sdk/clients/${path.basename(file.name, '.js')}`)
}

FAQ

Should I use Webpack instead of this plugin?

Browserify, in general, supports more modules, optimises better (generates smaller bundles), and requires less configuration. Webpack is an amazing tool, but it comes with several extras that are not really needed within a pure Node.js environment.

What about uglification? And babel?

You should be able to use uglify-es through uglifyify. For babel usage, babelify should do the trick. Refer back to Using browserify plugins section to set it up.

This other plugin I use is not playing ball with serverless-plugin-browserifier! What's up?

This plugin hijacks the normal serverless packaging process, so it will probably conflict with other plugins that use similar mechanisms. Please avoid mixing this plugin with other plugins that modify serverless' packaging behaviour.

Useful Information

License

MIT License.

This project has been forked from the original serverless-plugin-browserify and published under a different name, as the original has been abandoned.

For the complete information, please refer to the license file.