Learn how to use esbuild to bundle modules for the Fastly Compute JavaScript environment.
For more details about other starter kits for Compute, see the Fastly Documentation Hub
- Contains build steps configured to bundle your application using esbuild.
- Provides a starting point for an esbuild configuration for use with Fastly Compute.
- Demonstrates transpiling JSX syntax to JavaScript during bundling.
The example source code is a JSX file and holds dependencies on react and react-dom. It demonstrates serialization of a React component into a stream, served as a synthesized response from a Compute application.
import * as React from 'react';
import * as Server from 'react-dom/server';
const Greet = () => <h1>Hello, world!</h1>;
return new Response(
await Server.renderToReadableStream(<Greet />),
{
status: 200,
headers: {
'Content-Type': 'text/html',
},
},
);Compute applications written in JavaScript that have the standard structure and standard dependencies can be built using the tools included with the JavaScript SDK. However, if your application needs to perform advanced tasks at build time, such as replacing global modules, providing polyfills, or transforming code (such as JSX, TypeScript, or proposed JavaScript syntaxes), you can use a module bundler.
This starter kit demonstrates the use of esbuild for bundling, providing a configuration as a esbuild.config.js file that can be used as a starting point for configuring your application's specific bundling needs.
The esbuild package is declared as a dependency and run in a prebuild script, configured to place its output in an intermediate location. The build script then references those intermediate files as its input.
The esbuild package does not mandate a filename for configuration. Instead, esbuild is called via either a CLI or JavaScript API. This starter kit includes an esbuild.config.js file, which stores the configuration and calls esbuild.
At minimum, the configuration to bundle a Compute application for esbuild should include the following (pre-configured for this project):
entryPoints- The entry point source files provided as an array,['./src/index.jsx']in this app.bundle- Set totrue. Tells esbuild to run in bundle mode, in other words, to inline the dependency modules into the output file.platform- Set toneutral- Tells esbuild to use neutral defaults.outfile- Tells esbuild where to place the output bundled file,./dist/index.jsin this app.external- Set to[ 'fastly:*', ]. Indicates to esbuild thatfastly:imports should be looked up as external imports rather than modules undernode_modules.conditions- Set to['fastly'].- If you're using
react-dom, use['fastly', 'edge-light'].
- If you're using
import { build } from 'esbuild';
await build({
entryPoints: ['./src/index.jsx'],
bundle: true,
platform: 'neutral',
outfile: './dist/index.js',
external: [ 'fastly:*' ],
conditions: [ 'fastly', 'edge-light' ],
});Using these as a starting point, you can further customize the configuration to meet your needs. For example:
loader- can be used to determine how input files will be treated.alias- can be used to replace modules at build time.plugins- can be used to include plugins, which are modules that can inject code at variout points in time during bundling.- Refer to the esbuild Build options for more details.
Tip
See the Fastly Documentation section on module bundling for JavaScript for further hints.
The package.json file of this application includes the following scripts:
{
"scripts": {
"prebuild": "node esbuild.config.js",
"build": "js-compute-runtime ./dist/index.js ./bin/main.wasm",
// other scripts
}
}Building the application through fastly compute build (or indirectly by calling fastly compute serve or fastly compute publish) causes the following steps to run:
- The
fastly.tomlfile is consulted for itsscripts.buildvalue, resulting innpm run build. This instructs npm to execute thebuildscript. - Because
package.jsondefines aprebuildscript, npm first runs it:node esbuild.config.jsruns, using esbuild to bundlesrc/index.jsxand its imports into a single JS file,./dist/index.js. - npm runs the
buildscript: Thejs-compute-runtimeCLI tool (included as part of the@fastly/js-computepackage) wraps the bundled JS file into a Wasm file atbin/main.wasmand packages it into a.tar.gzfile ready for deployment to Compute.
By default, esbuild automatically applies the JSX loader for files with the .jsx extension, and transpiles JSX syntax to JavaScript during bundling. To exercise fine control over any options during this transformation, refer to the JSX loader reference in esbuild documentation.
The starter kit's package.json file sets "type": "module". This ensures .js source files are loaded as ES modules, enabling them to use the modern import and export syntax to interact with other modules and packages.
The starter kit is configured to use the condition names fastly and edge-light when resolving modules (conditions). These are taken into consideration during the bundling process when esbuild encounters a package that defines conditional exports.
For example, the index.jsx file in the starter kit declares an import on react-dom/server:
import Server from 'react-dom/server'; Because the condition name edge-light matches against one of the conditional exports listed in react-dom's package.json, esbuild resolves the package's entry point to a version of react-dom built for the edge.
To create an application using this starter kit, create a new directory for your application and switch to it, and then type the following command:
npm create @fastly/compute@latest -- --from=https://github.com/fastly/compute-starter-kit-javascript-esbuildTo build and run your new application in the local development environment, type the following command:
npm run startTo build and deploy your application to your Fastly account, type the following command. The first time you deploy the application, you will be prompted to create a new service in your account.
npm run deployBy default, esbuild pretty-prints the output bundle. In order to make the bundle smaller, the starter kit adds the minify configuration value when the bundle is built for production. To build in production mode, set the NODE_ENV environment variable to 'production' when building the bundle.
For example:
NODE_ENV=production npm run startThe starter kit doesn't require the use of any backends. Once deployed, you will have a Fastly service running on Compute that can generate synthetic responses at the edge.
This starter kit is configured to use additional packages to demonstrate the transpilation of JSX to JavaScript, and the use of React to render it to HTML.
If your application does not need React or JSX, you may remove this functionality using the following steps:
- Rename the
index.jsxfile toindex.js, and remove all code that uses the JSX syntax or that refers to thereactandreact-dompackages. - In
esbuild.config.js, modify theentryFilesfield from['./src/index.jsx']to['./src/index.js']to reflect this file name change. - In
esbuild.config.js, remove'edge-light'from theconditionsarray. - Remove the following dependencies from your application:
npm uninstall react react-dom
JSX is just one of the loaders provided by esbuild. Many others are provided by esbuild as well, to make various types of files available for loading as modules in your application. These can be mixed and matched, allowing your application to load anything it needs, including JSON files, CSS files, and raw files as text or binary. See esbuild loaders for a list of loaders.
If you need to load shims or polyfills to make functionality available to your Compute application, take a look at the inject option in the esbuild documentation.
If you need to redirect or alter rules related to module resolution, take a look at the Path Resolution guide in the esbuild documentation.
The esbuild bundler has many configuration options, but is designed in such a way that many of the defaults are sensible, so you only need to make changes that your application needs. Refer to the Build API guide in the esbuild documentation for further details.
Please see our SECURITY.md for guidance on reporting security-related issues.