• Stars
    star
    305
  • Rank 131,746 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Intelligently prepare Node.js Lambda functions for deployment

zip-it-and-ship-it

npm version Coverage Status Build Downloads

Creates Zip archives from Node.js, Go, and Rust programs. Those archives are ready to be uploaded to AWS Lambda.

This library is used under the hood by several Netlify features, including production CI builds, Netlify CLI and the JavaScript client.

Check Netlify documentation for:

Installation

npm install @netlify/zip-it-and-ship-it

Usage (Node.js)

zipFunctions(srcFolders, destFolder, options?)

  • srcFolders: string | Array<string>
  • destFolder: string
  • options: object?
  • Return value: Promise<object[]>
import { zipFunctions } from '@netlify/zip-it-and-ship-it'

const archives = await zipFunctions('functions', 'functions-dist', {
  archiveFormat: 'zip',
})

Creates Zip archives from Node.js, Go, and Rust programs. Those archives are ready to be uploaded to AWS Lambda.

srcFolders

A directory or a list of directories containing the source files. If a string is provided, the corresponding directory must exist. If an array of strings is provided, at least one directory must exist.

In Netlify, this directory is the "Functions folder".

A source folder can contain:

  • Sub-directories with a main file called index.js or {dir}.js where {dir} is the sub-directory name.
  • .js, .mjs, .cjs, .ts, .tsx, .mts or .cts files (Node.js)
  • .zip archives with Node.js already ready to upload to AWS Lambda.
  • Go programs already compiled. Those are copied as is.
  • Rust programs already compiled. Those are zipped.

destFolder

The directory where each .zip archive should be output. It is created if it does not exist. In Netlify CI, this is an unspecified temporary directory inside the CI machine. In Netlify CLI, this is a .netlify/functions directory in your build directory.

options

An optional object for customizing the behavior of the archive creation process.

archiveFormat

  • Type: string
  • Default value: zip

Format of the archive created for each function. Defaults to ZIP archives.

If set to none, the output of each function will be a directory containing all the bundled files.

basePath

  • Type: string
  • Default value: undefined

The directory which all relative paths will be resolved from. These include paths in the includedFiles config property, as well as imports using dynamic expressions such as require(\./files/${name}`)`.

config

  • Type: object
  • Default value: {}

An object matching glob-like expressions to objects containing configuration properties. Whenever a function name matches one of the expressions, it inherits the configuration properties.

The following properties are accepted:

  • externalNodeModules

    • Type: array<string>

    List of Node modules to include separately inside a node_modules directory.

  • ignoredNodeModules

    • Type: array<string>

    List of Node modules to keep out of the bundle.

  • nodeBundler

    • Type: string
    • Default value: zisi

    The bundler to use when processing JavaScript functions. Possible values: zisi, esbuild, esbuild_zisi or nft.

    When the value is esbuild_zisi, esbuild will be used with a fallback to zisi in case of an error.

  • nodeSourcemap

    • Type: boolean
    • Default value: false

    Whether to include a sourcemap file in the generated archive.

    Available only when nodeBundler is set to esbuild or esbuild_zisi.

  • nodeVersion

    • Type: string\
    • Default value: 18

    The version of Node.js to use as the compilation target for bundlers. This is also used to determine the runtime reported in the manifest. Any valid and supported Node.js version is accepted. Examples:

    • 14.x
    • 16.1.0
    • v18
    • nodejs18.x (for backwards compatibility)
  • rustTargetDirectory

    • Type: string
    • Default value: Path to a temporary directory

    The path to use as the Cargo target directory when bundling Rust functions from source. When a value is not specified, a random temporary directory will be used.

    The [name] placeholder will be replaced by the name of the function, allowing you to use it to construct the path to the target directory.

  • name

    • Type: string
    • Default value: undefined

    A name to use when displaying the function in the Netlify UI. Populates the displayName property in the functions manifest for the specified function.

  • generator

    • Type: string
    • Default value: undefined

    A field to use if the function has been autogenerated by a plugin or integration. A recommended format is @netlify/[email protected], where adding the version is highly appreciated.

featureFlags

See feature flags.

manifest

  • Type: string
  • Default value: undefined

Defines the full path, including the file name, to use for the manifest file that will be created with the functions bundling results. For example, path/to/manifest.json. This file is a JSON-formatted string with the following properties:

  • functions: An array with the functions created, in the same format as returned by zipFunctions
  • system.arch: The operating system CPU architecture, as returned by process.arch
  • system.platform: The operating system, as returned by process.platform
  • timestamp: The timestamp (in milliseconds) at the time of the functions bundling process
  • version: The version of the manifest file (current version is 1)

parallelLimit

  • Type: number
  • Default value: 5

Maximum number of functions to bundle at the same time.

internalSrcFolder

  • Type: string
  • Default value: undefined

Defines the path to the folder with internal functions. Used to populate a function's generator property if generator is not configured in the function's config itself, if its path is within this specified internal functions folder.

Return value

This returns a Promise resolving to an array of objects describing each archive. Every object has the following properties.

  • mainFile: string

    The path to the function's entry file.

  • name: string

    The name of the function.

  • path: string

    Absolute file path to the archive file.

  • runtime string

    Either "js", "go", or "rs".

  • size: number

    The size of the generated archive, in bytes.

  • displayName: string

    If there was a user-defined configuration object applied to the function, and it had a name defined. This will be returned here.

  • generator: string

    If there was a user-defined configuration object applied to the function, and it had generator defined. This will be returned here. If there was nothing defined, but an internalSrcFolder was passed and the function was defined in there, it will return a string to specify it was an internal function.

Additionally, the following properties also exist for Node.js functions:

  • bundler: string

    Contains the name of the bundler that was used to prepare the function.

  • bundlerErrors: Array<object>

    Contains any errors that were generated by the bundler when preparing the function.

  • bundlerWarnings: Array<object>

    Contains any warnings that were generated by the bundler when preparing the function.

  • config: object

    The user-defined configuration object that was applied to a particular function.

  • inputs: Array<string>

    A list of file paths that were visited as part of the dependency traversal. For example, if my-function.js contains require('./my-supporting-file.js'), the inputs array will contain both my-function.js and my-supporting-file.js.

  • nativeNodeModules: object

    A list of Node modules with native dependencies that were found during the module traversal. This is a two-level object, mapping module names to an object that maps the module path to its version. For example:

    {
      "nativeNodeModules": {
        "module-one": {
          "/full/path/to/the/module": "1.0.0",
          "/another/instance/of/this/module": "2.0.0"
        }
      }
    }
  • nodeModulesWithDynamicImports: Array<string>

    A list of Node modules that reference other files with a dynamic expression (e.g. require(someFunction()) as opposed to require('./some-file')). This is an array containing the module names.

  • runtimeAPIVersion number | undefined

    When a function with the new API will be detected this is set to 2. Otherwise it is set to 1. undefined is only returned in case of an error.

  • runtimeVersion string | undefined

    Which exact runtime this function should be using. (e.g. nodejs18.x). This value is detected based on the input nodeVersion.

zipFunction(srcPath, destFolder, options?)

  • srcPath: string
  • destFolder: string
  • options: object?
  • Return value: object | undefined
import { zipFunction } from '@netlify/zip-it-and-ship-it'

const archive = await zipFunction('functions/function.js', 'functions-dist')

This is like zipFunctions() except it bundles a single Function.

The return value is undefined if the function is invalid.

listFunctions(srcFolders, options?)

Returns the list of functions to bundle.

import { listFunctions } from '@netlify/zip-it-and-ship-it'

const functions = await listFunctions('functions/function.js')

srcFolders

A directory or a list of directories containing the source files. If a string is provided, the corresponding directory must exist. If an array of strings is provided, at least one directory must exist.

options

An optional options object.

featureFlags

See feature flags.

Return value

Each object has the following properties:

  • name: string

    Function's name. This is the one used in the Function URL. For example, if a Function is a myFunc.js regular file, the name is myFunc and the URL is https://{hostname}/.netlify/functions/myFunc.

  • displayName: string

    If there was a user-defined configuration object applied to the function, and it had a name defined. This will be returned here.

  • mainFile: string

    Absolute path to the Function's main file. If the Function is a Node.js directory, this is its index.js or {dir}.js file.

  • runtime: string

    Either "js", "go", or "rs".

  • extension: string

    Source file extension. For Node.js, this is either .js, .ts or .zip. For Go, this can be anything.

  • generator: string

    If there was a user-defined configuration object applied to the function, and it had generator defined. This will be returned here.

listFunctionsFiles(srcFolders)

Like listFunctions(), except it returns not only the Functions main files, but also all their required files. This is much slower.

import { listFunctionsFiles } from '@netlify/zip-it-and-ship-it'

const functions = await listFunctionsFiles('functions/function.js')

srcFolders

A directory or a list of directories containing the source files. If a string is provided, the corresponding directory must exist. If an array of strings is provided, at least one directory must exist.

options

An optional options object.

featureFlags

See feature flags.

Return value

The return value is the same as listFunctions() but with the following additional properties.

  • srcFile: string

    Absolute file to the source file.

Usage (CLI)

$ zip-it-and-ship-it srcFolder destFolder

The CLI performs the same logic as zipFunctions(). The archives are printed on stdout as a JSON array.

Bundling Node.js functions

zip-it-and-ship-it uses two different mechanisms (bundlers) for preparing Node.js functions for deployment. You can choose which one to use for all functions or on a per-function basis.

zisi

This is the default bundler.

When using the zisi bundler, the following files are included in the generated archive:

  • All files/directories within the same directory (except node_modules)
  • All the files referenced using static require() calls
    • Example (user file): require('./lib/my-file')
    • Example (Node module): require('date-fns')

The following files are excluded:

  • @types/* TypeScript definitions
  • aws-sdk (on Node v16 and earlier)
  • @aws-sdk/* (on Node v18 and later)
  • Temporary files like *~, *.swp, etc.

esbuild

The esbuild bundler can generate smaller archives due to its tree-shaking step. It's also a lot faster. You can read more about it on the Netlify Blog.

When using esbuild, only the files that are directly required by a function or one of its dependencies will be included. For example, a Node module has 1,000 files but your function only requires one of them, the other 999 will not be included in the bundle.

You can enable esbuild by setting the config option when calling zipFunction or zipFunctions:

import { zipFunctions } from '@netlify/zip-it-and-ship-it'

const archives = await zipFunctions('functions', 'functions-dist', {
  config: {
    // Applying these settings to all functions.
    '*': {
      nodeBundler: 'esbuild',
    },
  },
})

Feature flags

zip-it-and-ship-it uses feature flags to enable or disable features during their testing or deprecation periods.

These are supplied to each of the entrypoint functions (zipFunction, zipFunctions, listFunctions and listFunctionsFiles) as a named parameter called featureFlags. It consists of an object where each key is the name of a feature flag and the values are Booleans indicating whether each feature flag is enabled or disabled.

The list of all feature flags currently being used can be found here.

Troubleshooting

Build step

zip-it-and-ship-it does not build, transpile nor install the dependencies of the Functions. This needs to be done before calling zip-it-and-ship-it.

Missing dependencies

If a Node module require() another Node module but does not list it in its package.json (dependencies, peerDependencies or optionalDependencies), it is not bundled, which might make the Function fail.

More information in this issue.

Conditional require

Files required with a require() statement inside an if or try/catch block are always bundled.

More information in this issue.

Dynamic require

Files required with a require() statement whose argument is not a string literal, e.g. require(variable), are never bundled.

More information in this issue.

Node.js native modules

If your Function or one of its dependencies uses Node.js native modules, the Node.js version used in AWS Lambda might need to be the same as the one used when installing those native modules.

In Netlify, this is done by ensuring that the following Node.js versions are the same:

Note that this problem might not apply for Node.js native modules using the N-API.

More information in this issue.

File Serving

As of v0.3.0 the serveFunctions capability has been extracted out to Netlify Dev.

More Repositories

1

netlify-cms

A Git-based CMS for Static Site Generators
JavaScript
16,192
star
2

gotrue

An SWT based API for managing users and issuing SWT tokens.
Go
3,530
star
3

staticgen

StaticGen.com, A leaderboard of top open-source static site generators
JavaScript
2,471
star
4

cli

Netlify Command Line Interface
TypeScript
1,543
star
5

gocommerce

A headless e-commerce for JAMstack sites.
Go
1,465
star
6

netlify-identity-widget

A zero config, framework free Netlify Identity widget
JavaScript
735
star
7

next-on-netlify

Build and deploy Next.js applications with Server-Side Rendering on Netlify!
JavaScript
720
star
8

headlesscms.org

Source for headlesscms.org
JavaScript
628
star
9

netlify-lambda

Helps building and serving lambda functions locally and in CI environments
JavaScript
601
star
10

next-runtime

The Next.js Runtime allows Next.js to run on Netlify with zero configuration
TypeScript
575
star
11

functions.netlify.com

Tutorials, examples, workshops and a playground for serverless with Netlify Functions
SCSS
515
star
12

build-image

This is the build image used for running automated builds
Shell
498
star
13

gotrue-js

JavaScript client library for GoTrue
JavaScript
457
star
14

create-react-app-lambda

JavaScript
414
star
15

netlify-faunadb-example

Using FaunaDB with netlify functions
JavaScript
388
star
16

actions

Shell
360
star
17

git-gateway

A Gateway to Git APIs
Go
355
star
18

gotell

Netlify Comments is an API and build tool for handling large amounts of comments for JAMstack products
Go
276
star
19

explorers

JavaScript
262
star
20

million-devs

Microsite for the 1 Million Developers announcement.
Vue
250
star
21

netlify-statuskit

Netlify StatusKit is a template to deploy your own Status pages on Netlify.
HTML
237
star
22

open-api

Open API specification of Netlify's API
Go
234
star
23

js-client

A Open-API derived JS + Node.js API client for Netlify
JavaScript
214
star
24

build

Netlify Build (node process) runs the build command, Build Plugins and bundles Netlify Functions. Can be run in Buildbot or locally using Netlify CLI
TypeScript
207
star
25

netlify-plugin-lighthouse

Netlify Plugin to run Lighthouse on each build
JavaScript
198
star
26

netlifyctl

Go
178
star
27

netlify-dev-plugin

Local dev server with functions, rules engine and add-on support
JavaScript
176
star
28

framework-info

Framework detection utility
JavaScript
136
star
29

jekyll-srcset

Dead simple responsive images for jekyll
Ruby
136
star
30

gocommerce-js

A gocommerce client library
JavaScript
130
star
31

jekyll-gdrive

Access a Google Drive Spreadsheet from your Jekyll templates
Ruby
116
star
32

plugins

Netlify plugins directory.
JavaScript
95
star
33

prerender

Automatically rendering JS-driven pages for crawlers and social sharing
JavaScript
94
star
34

netlify-playground

89
star
35

netlify-plugin-gatsby

A build plugin to integrate Gatsby seamlessly with Netlify
TypeScript
88
star
36

code-examples

Code snippets for customers
HTML
87
star
37

labs

Documentation and samples for Netlify Labs features.
76
star
38

templates

This is board to showcase templates and boilerplates https://templates.netlify.com
Nunjucks
76
star
39

vue-cli-plugin-netlify-lambda

Netlify Lambda plugin for Vue CLI
JavaScript
76
star
40

remix-template

Deploy your Remix site to Netlify Edge Functions
JavaScript
73
star
41

netlify-cms-widget-starter

A boilerplate for creating Netlify CMS widgets.
JavaScript
73
star
42

classnames-template-literals

Small utility to format long classnames with template literals
JavaScript
70
star
43

gotiator

A tiny JWT based API gateway
Go
70
star
44

matterday.netlify.com

A site that asks us what we could do with more time.
CSS
70
star
45

react-server-components-demo

Minimal implementation on server components via Netlify functions
JavaScript
67
star
46

edge-functions-examples

Explore a library of reference examples for learning about Edge Functions on Netlify.
JavaScript
67
star
47

binrc

Binrc is a command line application to manage different versions of binaries stored on GitHub releases.
Makefile
52
star
48

next-on-netlify-demo

Demo of a Next.js app with Server-Side Rendering on Netlify
JavaScript
52
star
49

go-functions-example

Go
49
star
50

petsofnetlify

pets of netlifiers
Nunjucks
47
star
51

full-react-server-demo

JavaScript
45
star
52

rust-functions-example

Deploy Rust lambda functions on Netlify
Rust
45
star
53

culture-handbook

The philosophy and values of Netlify's diverse, globally distributed workforce
44
star
54

gojoin

Mini API wrapping Stripes Subscriptions for Single Page Aps and JAMstack sites
Go
41
star
55

netlify-git-api

Go
41
star
56

gatsby-parallel-runner

JavaScript
38
star
57

functions

JavaScript and TypeScript utilities for Netlify Functions.
TypeScript
38
star
58

elastinats

Go
36
star
59

netlify-photo-gallery

HTML
35
star
60

gocommerce-admin

Admin UI for Netlify Commerce
JavaScript
35
star
61

addons

Netlify add-on documentation
34
star
62

ask-netlify

A place to submit questions for Netlify to answer in tutorials, podcasts and blog posts
HTML
34
star
63

netlify-auth-demo

Demo for integrating GitHub OAuth with a Netlify site
HTML
33
star
64

explorers-up-and-running-with-serverless-functions

Free resource for learning how to use serverless functions!
HTML
31
star
65

hydrogen-netlify-starter

Get started with Hydrogen on Netlify
JavaScript
31
star
66

build-plugin-template

Template repository to create new Netlify Build plugins.
JavaScript
30
star
67

twickr

Twickr lets you send tweets of interest from Twitter to Slack
Go
30
star
68

remix-compute

Remix adapter and server runtime for Netlify
TypeScript
29
star
69

www-post-scheduler

This is a serverless function to auto publish blog posts
JavaScript
28
star
70

postcss-fout-with-a-class

Rewrite all selectors that will trigger a font load to be scoped under a class
JavaScript
28
star
71

micro-api-client

Small library for talking to micro REST APIs (not related to Netlify's main API)
JavaScript
28
star
72

next-edge-middleware

JavaScript
27
star
73

vue-lambda-starter

Starter Template for Vue + AWS Lambda with Netlify
Vue
27
star
74

netlify-browser-extension

netlify-chrome-extension
JavaScript
26
star
75

make-wp-epic

Migration tool for moving from WordPress to Victor Hugo
JavaScript
26
star
76

hydrogen-platform

Hydrogen support for Netlify Edge Functions
TypeScript
26
star
77

netlify-redirect-parser

Library for parsing Netlify redirects
JavaScript
23
star
78

next-react-server-components

JavaScript
22
star
79

netlify-auth-providers

JS library to use Netlify's OAuth providers
JavaScript
22
star
80

explorers-composition-api

Learn how the Composition API works in this Jamstack Explorers mission!
Vue
20
star
81

vite-plugin-netlify-edge

Netlify Edge Function support for Vite
TypeScript
19
star
82

angular-runtime

The Angular Runtime allows Angular to run on Netlify with zero configuration
JavaScript
18
star
83

mailme

MailMe sends mails with stylish templates
Go
18
star
84

eslint-config-node

ESLint, Prettier and Editorconfig shared by Netlify's Node.js projects
JavaScript
18
star
85

slate-markdown-serializer

JavaScript
17
star
86

delta-action

A GitHub Action for capturing benchmark data and tracking its variation against a baseline
JavaScript
17
star
87

netlify-credential-helper

Git credential helper to use Netlify's API as authentication backend
Go
16
star
88

netlify-cms-www

Former repo for netlifycms.org. Moved to the code repo at
CSS
15
star
89

go-client

Depreciated repo: home of the old go client. See netlify/open-api for the new home of the go client
Go
15
star
90

verify-okta

Small Lambda function for verifying and gating content with Okta
Go
14
star
91

netlify-oauth-example

JavaScript
14
star
92

fauna-one-click

Moved https://github.com/netlify/netlify-faunadb-example
JavaScript
13
star
93

screenshot

Take screenshots of websites
Shell
13
star
94

netlify-comments-starter

Start project for Netlify Comments
13
star
95

node-template

Netlify's Node.js repository template
Python
13
star
96

godoc-static

Generates static HTML of documentation of Go libraries
Go
12
star
97

streamer

tail files and send them to nats
Go
12
star
98

edge-bundler

Intelligently prepare Netlify Edge Functions for deployment
TypeScript
12
star
99

ruby-client

Netlify API client for Ruby
Ruby
11
star
100

gatsby-plugin-netlify

Gatsby plugin. Automatically generates a _headers file and a _redirects file at the root of the public folder to configure HTTP headers and redirects on Netlify.
TypeScript
11
star