npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

serverless-plugin-browserifier

v3.1.1

Published

Serverless plugin that uses browserify to bundle Node.js lambda functions

Downloads

2,180

Readme

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.