Skip to the content

Build tools

Set up webpack, Rspack, Rollup, esbuild, Next.js or SWC. A test in CI builds and examines each setup.

A native await does not use a function that a library can patch. Thus, a compiler must change each async function into a generator. The transform page tells how the runtime then keeps the context. There are two methods:

MethodRulesTools
The Babel preset of the libraryAll rulesVite, webpack, Rspack, Rollup, esbuild, Next.js, and each tool that can use Babel
The target ES2016 of a compilerAll rules except rule C5. The callback hooks get no name for the steps after an await.SWC, esbuild, TypeScript, and Next.js without Babel

Use the Babel preset if your build tool can use Babel. Use the target ES2016 if your build tool cannot use Babel, or if you do not want a Babel step.

The tested setups

The command pnpm test:bundlers builds the same page with each setup, and opens the page in Chromium. The page examines the context after await, in a callback of a dependency in node_modules, in a generator and in an event of the browser. The Next.js page also starts a server action and a "use cache" function. CI starts this test for each change.

ToolSetupRules
Vite 8The plugin asyncContext()All rules (pnpm smoke)
webpack 5babel-loader with the presetAll rules
Rspack 2babel-loader with the presetAll rules
Rspack 2builtin:swc-loader with the target ES2016All rules except rule C5
Rollup 4@rollup/plugin-babel with the presetAll rules
esbuild 0.28A plugin that applies the presetAll rules
esbuild 0.28The target es2016All rules except rule C5
Next.js 16, TurbopackA rule with babel-loader and the presetAll rules
Next.js 16, TurbopackA Babel configuration fileAll rules
Next.js 16, webpackA Babel configuration fileAll rules
Next.js 16, TurbopackA browserslist query with a browser without async functionsAll rules except rule C5

The configurations of the test are in test/bundlers/fixture/build.mjs, test/bundlers/fixture/next/ and test/bundlers/fixture/next-rule/.

Vite

Add the plugin asyncContext() to vite.config.ts. The get started page tells how.

webpack

  1. Install babel-loader. For TypeScript and JSX files, also install @babel/preset-typescript and @babel/preset-react.
  2. Add a rule for all JavaScript and TypeScript files, with the preset of the library.
  3. Do not exclude node_modules. Then the preset also transforms the dependencies.
// webpack.config.js
export default {
    module : {
        rules : [{
            test : /\.[cm]?[jt]sx?$/,
            use : {
                loader : "babel-loader",
                options : {
                    presets : ["@babel/preset-react", "@babel/preset-typescript", "async-browser-context/babel-preset"],
                },
            },
        }],
    },
};

Babel cannot read TypeScript and JSX without @babel/preset-typescript and @babel/preset-react. For a project with JavaScript only, remove them. If your configuration has other presets, put the preset of the library last.

Rspack

Rspack can use babel-loader. Use the same rule as for webpack. With this rule, Rspack uses Babel for your code, and the build takes more time.

Rspack can also compile with its own SWC loader. Set the target es2016. SWC then changes each async function into a generator:

// rspack.config.js
export default {
    module : {
        rules : [{
            test : /\.[cm]?js$/,
            loader : "builtin:swc-loader",
            options : { jsc : { target : "es2016" } },
            type : "javascript/auto",
        }],
    },
};

For TypeScript, add the parser options of your project to jsc. The section What the target ES2016 does not keep tells the differences.

Rollup

  1. Install @rollup/plugin-babel and @rollup/plugin-node-resolve.
  2. Add the two plugins. The Babel plugin transforms all modules, also in node_modules.
// rollup.config.js
import { babel } from "@rollup/plugin-babel";
import { nodeResolve } from "@rollup/plugin-node-resolve";

export default {
    input : "src/main.js",
    output : { dir : "dist", format : "es" },
    plugins : [
        nodeResolve({ browser : true }),
        babel({ babelHelpers : "bundled", presets : ["async-browser-context/babel-preset"] }),
    ],
};

esbuild

esbuild does not use Babel. A small plugin can apply the preset to each module before esbuild compiles it:

// build.js
import fs from "node:fs";
import path from "node:path";
import * as babel from "@babel/core";
import * as esbuild from "esbuild";

const asyncContext = {
    name : "async-browser-context",
    setup(build) {
        build.onLoad({ filter : /\.[cm]?[jt]sx?$/ }, async (args) => {
            const source = await fs.promises.readFile(args.path, "utf8");
            if (!/\basync\b|\byield\b|function\s*\*/.test(source)) {
                return undefined;
            }
            const typescript = /\.[cm]?tsx?$/.test(args.path);
            const result = await babel.transformAsync(source, {
                filename : args.path,
                babelrc : false,
                configFile : false,
                sourceType : "unambiguous",
                parserOpts : { plugins : typescript ? ["typescript", "jsx"] : ["jsx"] },
                presets : ["async-browser-context/babel-preset"],
            });
            const loader = path.extname(args.path).slice(1).replace(/^[cm]/, "");
            return { contents : result.code, loader };
        });
    },
};

await esbuild.build({ entryPoints : ["src/main.js"], bundle : true, format : "esm", outdir : "dist", plugins : [asyncContext] });

The plugin keeps the TypeScript and JSX syntax, and esbuild compiles it after the plugin.

Without the plugin, set the target es2016. esbuild then changes each async function into a generator. With this target, esbuild does not accept a top-level await.

Next.js

CI builds and examines three setups with Next.js 16. The page of the test also starts a server action, which starts a "use cache" function.

SetupRulesThe code that changesUse it
A Turbopack ruleAll rulesThe files of the browser with async functions or generators, also in node_modulesWith Turbopack. This is the recommended setup.
A Babel configuration fileAll rulesAll your code, on the server and in the browser, and the packages in transpilePackagesWith webpack (next build --webpack)
SWC with a browserslist queryAll rules except rule C5All the code of the browser, also in node_modulesIf you do not want Babel

A Turbopack rule

Install babel-loader. Then add a rule for each kind of file to next.config.mjs:

// next.config.mjs
/** The options of babel-loader for one kind of file. */
function babel(syntax) {
    return {
        loader : "babel-loader",
        options : {
            babelrc : false,
            configFile : false,
            sourceType : "unambiguous",
            parserOpts : { plugins : syntax },
            presets : ["async-browser-context/babel-preset"],
        },
    };
}

/** The files of the browser with async functions or generators. */
const condition = { all : ["browser", { content : /\basync\b|\byield\b|function\s*\*/ }] };

export default {
    turbopack : {
        rules : {
            "*.{js,jsx,mjs,cjs}" : { condition, loaders : [babel(["jsx"])] },
            "*.{ts,mts,cts}" : { condition, loaders : [babel(["typescript"])] },
            "*.tsx" : { condition, loaders : [babel(["typescript", "jsx"])] },
        },
    },
};
  • The loader applies only the preset of the library. Babel reads the TypeScript and JSX syntax (parserOpts), but it does not change it. After the loader, SWC compiles the file as usual.
  • A .ts file cannot have JSX. Thus TypeScript files and TSX files have different rules.
  • Turbopack gives the options of a loader as JSON. Thus use only names, strings, numbers and lists in options. Do not use functions or regular expressions there.
  • The browser condition selects the code of the browser. On the server, the node export condition selects the Node.js entry of the library, which uses the native AsyncLocalStorage. The server code thus does not need the transform.
  • The rule also applies to the packages in node_modules. To exclude a file or a package, add a condition to the all list, for example { not : { path : /node_modules\/some-package\// } }. { not : "foreign" } excludes all of node_modules. A callback that a package starts after its own await then gets the root context (refer to the dependencies).

The configuration of the test is in test/bundlers/fixture/next-rule/next.config.mjs.

Server Actions and "use cache"

The preset does not change the server code of React Server Components: a file or a function with the directive "use server", "use cache" or "use cache: <kind>". Next.js accepts only native async functions there. Thus you do not exclude these files from a rule. In the bundle of the browser, Next.js replaces a server action with a reference to the server. The server keeps the context with the native AsyncLocalStorage.

The preset changes the other functions of the file. For example, an async page function can have a server action in it. The page function changes, and the server action stays a native async function.

The preset of version 0.3.1 and earlier changed these functions, and Next.js then stopped the build.

pnpm

The preset adds an import of async-browser-context/runtime to each file that it changes, also to the files of dependencies. Thus each dependency that the rule changes must find the library from its own folder. With pnpm, this depends on the settings:

pnpm settingA dependency finds the runtimeWhat to do
The default hoistPattern (*)Yes, in node_modules/.pnpm/node_modulesNothing
hoist: false, or a hoistPattern without async-browser-contextNoAdd async-browser-context to publicHoistPattern, or add the alias below
enableGlobalVirtualStore: trueNoAdd the alias below

The alias sends each import of the runtime in the browser to one file. The path goes from the folder of next.config.mjs to the node_modules folder with the library. In a monorepo, this can be ../../node_modules.

// next.config.mjs
export default {
    turbopack : {
        resolveAlias : {
            "async-browser-context/runtime" : { browser : "./node_modules/async-browser-context/dist/runtime.js" },
        },
        rules : { /* the rules above */ },
    },
};

Performance

Babel is slower than SWC. The rule above gives Babel only the files of the browser with the words async, yield or function* (the content condition). SWC compiles all the other files without Babel. The Vite plugin of the library uses the same filter.

A file that Babel changes gets generators in place of async functions, and it uses the runtime. Thus the bundle gets larger. The cost depends on the number of files with async functions in your code and in your dependencies. Compare the time of next build and the size of the bundle with and without the rule. To make Babel do less work, exclude packages with a path condition. Exclude only the packages that do not start your code after an await.

The build tool test writes the time of each Next.js build to its output. These times come from one build of a small page, so they are not a benchmark.

A Babel configuration file

  1. Add a Babel configuration file next to package.json, with the preset of Next.js and the preset of the library. Give the browsers of Next.js to @babel/preset-env in next/babel:

    // babel.config.js
    module.exports = {
        presets : [
            ["next/babel", { "preset-env" : { targets : "chrome 111, edge 111, firefox 111, safari 16.4" } }],
            "async-browser-context/babel-preset",
        ],
    };
  2. Add the dependencies that start your callbacks after an await to transpilePackages:

    // next.config.mjs
    export default { transpilePackages : ["some-dependency"] };

With webpack, next/babel also compiles the code of the browser with @babel/preset-env. Next.js does not give it the browsers of its SWC configuration. Without targets and without a browserslist query, preset-env changes all the code for old browsers. It also changes the async functions of each server action that a client component imports. Next.js then stops the build with the error "Server Actions must be async functions". This occurs also without the preset of the library.

The targets above are the default browsers of Next.js 16. A browserslist query in package.json can replace them, but each browser in the query must have native async functions. On the server, next/babel uses the version of Node.js that builds the app.

With a Babel configuration file, Next.js uses Babel in place of SWC for all your code, with Turbopack and with webpack. The build takes more time. Next.js does not apply the Babel configuration to the other packages in node_modules. With Turbopack, use the rule: SWC then compiles all the other files.

The server code also gets the transform. On the server, the node export condition selects the Node.js entry of the library, which uses the native AsyncLocalStorage. The preset does not change server actions and "use cache" functions (refer to Server Actions).

SWC with a browserslist query

Next.js can also keep SWC for all files. Add a browser without async functions to the browserslist query of package.json, for example "chrome 54". SWC then changes each async function into a generator. Turbopack applies the query also to node_modules. The webpack mode of Next.js does not, so it needs transpilePackages.

This setup keeps all rules except rule C5, and the callback hooks get no names (refer to what the target ES2016 does not keep). The query also changes all newer syntax, so the bundles get larger. The library has no SWC plugin.

SWC

SWC cannot use Babel presets, and the library has no SWC plugin. Set the target es2016 in .swcrc:

{
    "jsc": { "target": "es2016" }
}

Apply SWC also to the dependencies in node_modules.

Other tools

A tool that reads a Babel configuration file can use the preset, for example Parcel. CI does not examine these tools. Use the checks of the test (test/smoke/fixture/checks.js) to examine your setup.

Minifiers

The preset does not change the runtime of the library. It finds the native async functions of the runtime by the directive "async-browser-context runtime". Terser and other minifiers can remove directives. Thus apply the preset before the minifier. Do not apply the preset to a copy of the runtime that a minifier changed. An example is a dependency that bundles and minifies this library.

The setups on this page minify after the transform of each module, so they are correct. The Vite plugin also skips the files of the runtime by their path.

The dependencies

A dependency with native async functions continues after its own await without the context. A callback that the dependency starts after that await gets the root context (rule C7). It does not get the context of a different operation. Each setup on this page also transforms node_modules, except the Babel configuration file of Next.js, which needs transpilePackages.

A dependency that its authors compiled to generators before the publish needs nothing. Examples are the __awaiter helper of TypeScript and _asyncToGenerator of Babel. The helpers continue in then callbacks, and the patch of then keeps the context.

What the target ES2016 does not keep

The target ES2016 changes each async function into a generator with then callbacks. The patch of then gives each callback the context of the step that started it. The command pnpm test:node starts all rule tests with SWC and with esbuild in place of the preset. All tests pass, except these:

  • Rule C5. A generator body gets the context of each next() call, as with AsyncLocalStorage of Node.js. With the preset, a generator body gets the context of the call that made the generator.
  • The names of the callback hooks. The hooks get each step after an await as a then callback of the helper of the compiler. The source is "Promise.then", and the function is the helper.
  • The size. The target also changes the syntax that is newer than ES2016, for example ?. and object spread. The size table shows the cost.

The esbuild project does not start the test file of probe P10, because esbuild cannot change its top-level for await for the target ES2016.

async-browser-context: AsyncLocalStorage and the TC39 AsyncContext API for browsers. The source code is on GitHub.

To change a page, edit its file in site/content/. The writing style guide tells you how.

An AI model (Claude, from Anthropic) wrote most of the text and the code of this site and of the library, under the direction of the author. The tests and the STE linter examine them.