new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · Wrangler · all subjects

wrangler/bundling

55 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Custom Builds escape hatch for bundling

Custom Builds provides an escape hatch that lets you run your own build before Wrangler's built-in bundling, offering more flexibility when Wrangler's inbuilt bundling does not meet your needs.

Non-JavaScript modules supported in bundling

Wrangler supports the following file types as non-JavaScript modules that can be imported at runtime: .txt (imported as string), .html (imported as string), .sql (imported as string), .bin (imported as ArrayBuffer), .wasm and .wasm?module (imported as WebAssembly.Module). These files are uploaded as separate modules rather than bundled into the entry-point file.

Import example for text file

Example of importing a text file: import text from "./example.txt"; The variable 'text' will be a string containing the contents of example.txt.

Wrangler uses esbuild for bundling by default

By default, Wrangler bundles Worker code using esbuild. This provides built-in support for importing modules from npm defined in package.json. Wrangler periodically updates the esbuild version, and since esbuild is a pre-1.0.0 tool, this may sometimes include breaking changes to bundling behavior, including in Wrangler minor versions.

Import and instantiate WASM module example

Example of importing and using a WASM module: import wasm from "./example.wasm"; const instance = await WebAssembly.instantiate(wasm); export default { fetch() { const result = instance.exports.exported_func(); return new Response(result); }, };

WebAssembly.instantiateStreaming not supported

Cloudflare Workers does not support WebAssembly.instantiateStreaming().

Lazy imports with find_additional_modules

When 'find_additional_modules' is true and a matching rule is added for a large lazy-imported file (for example, 'await import("./large-dep.mjs")'), that file is only loaded and executed at runtime when it is actually imported, rather than being bundled directly into the entrypoint.

Dynamic imports with find_additional_modules example

Variable based dynamic imports (for example, 'await import(`./lang/${language}.mjs`)') require a rule matching those files to be available at runtime. A rule like '{ "type": "EsModule", "globs": ["./lang/**/*.mjs"], "fallthrough": true }' ensures these modules are included in the upload.

process.env.NODE_ENV values by Wrangler command

process.env.NODE_ENV is statically replaced at build time based on the command: 'wrangler dev' sets it to 'development', while 'wrangler deploy' or 'wrangler build' sets it to 'production'. Development-only code can be removed from the production bundle.

Override NODE_ENV during bundling

You can override the default NODE_ENV value by setting the NODE_ENV environment variable when running a Wrangler command, for example: 'NODE_ENV=staging npx wrangler dev'.

Conditional exports field in package.json

Wrangler respects the conditional 'exports' field in package.json, which allows developers to implement isomorphic libraries with different implementations depending on the JavaScript runtime. When bundling, Wrangler will try to load the 'workerd' key from the conditional exports.

WRANGLER_COMMAND environment variable in custom builds

When Wrangler runs a custom build command, it sets the WRANGLER_COMMAND environment variable so the build script can detect which Wrangler command triggered the build. This allows customization of the build process based on the deployment context. The possible values are: 'dev' for wrangler dev, 'deploy' for wrangler deploy, 'versions upload' for wrangler versions upload, and 'types' for wrangler types.

Using WRANGLER_COMMAND to differentiate dev and production builds

A custom build script can check the WRANGLER_COMMAND environment variable to apply different build settings for development and production. For example: ```bash #!/bin/bash if [ "$WRANGLER_COMMAND" = "dev" ]; then echo "Building for development..." # run a development build else echo "Building for production..." # run a production build fi ``` This allows the build process to optimize differently depending on whether it is being triggered by wrangler dev or wrangler deploy.

build configuration field

The build field is an optional Build object that configures a custom build step to be run by Wrangler when building the Worker. Not applicable if using the Cloudflare Vite plugin.

no_bundle configuration field

The no_bundle field is an optional boolean that skips internal build steps and directly deploys the Worker script. Must have a plain JavaScript Worker with no dependencies. Not applicable if using the Cloudflare Vite plugin.

find_additional_modules configuration field

The find_additional_modules field is an optional boolean. If true, Wrangler will traverse the file tree below base_dir. Any files that match rules will be included in the deployed Worker. Defaults to true if no_bundle is true, otherwise false. Can only be used with Module format Workers (not Service Worker format). Not applicable if using the Cloudflare Vite plugin.

base_dir configuration field

The base_dir field is an optional string that specifies the directory in which module rules should be evaluated when including additional files (via find_additional_modules) into a Worker deployment. Defaults to the directory containing the main entry point of the Worker if not specified. Not applicable if using the Cloudflare Vite plugin.

preserve_file_names configuration field

The preserve_file_names field is an optional boolean that determines whether Wrangler will preserve the file names of additional modules bundled with the Worker. The default is to prepend filenames with a content hash. For example, 34de60b44167af5c5a709e62a4e20c4f18c9e3b6-favicon.ico. Not applicable if using the Cloudflare Vite plugin.

minify configuration field

The minify field is an optional boolean that minifies the Worker script before uploading. If using the Cloudflare Vite plugin, minify is replaced by Vite's build.minify option.

keep_names configuration field

The keep_names field is an optional boolean that specifies whether esbuild should apply its keepNames logic to the code. Wrangler uses esbuild to process the Worker code for development and deployment. Defaults to true.

Bundling configuration: rules field

The rules field is an array of objects that specify additional modules to include in your Worker. Each rule has type (string, required, one of ESModule, CommonJS, CompiledWasm, Text, or Data), globs (string array, required, glob patterns like ["**/*.md"]), and fallthrough (boolean, optional, allows multiple rules for same type).

find_additional_modules option for bundling

Setting find_additional_modules to true in the configuration file causes Wrangler to traverse the file tree below base_dir (which defaults to the directory containing the main entrypoint). Any files matching rules will be included as unbundled, external modules.

Python Workers module configuration

Python Workers bundle files and folders in python_modules at the root of the Worker (alongside wrangler config). The python_modules.excludes option excludes files from being included. By default, python_modules.excludes is set to ["**/*.pyc"], which should be included when setting a different value.

Module aliasing strategies for bundling issues

When using module aliasing to fix bundling issues, you have three options: (1) Alternative implementation — implement the module's logic in a Worker-compatible manner, (2) No-op module — point alias to an empty file if the module is unused, (3) Runtime error — point alias to a file with a throw statement if the module should never be used.

Wrangler v2 introduces TypeScript support

Wrangler v2 introduces TypeScript support. You can give wrangler a TypeScript file, and it will automatically transpile it to JavaScript using esbuild under-the-hood.

webpack_config and webpack properties no longer supported in Wrangler v2

The webpack_config and webpack configuration properties are no longer supported in Wrangler v2. Refer to the webpack migration guide to modify your project and use a custom build instead.

Wrangler v2 no longer assumes bare specifiers are file names

Wrangler v2 will no longer assume that bare specifiers are file names if they are not represented as a path. For example, import SomeDependency from "some-dependency.js"; should be rewritten to import SomeDependency from "./some-dependency.js"; to specify that it is a relative path. In Wrangler v1, the bare specifier would be resolved to the file, but in Wrangler v2 this logs a deprecation warning and will break with an error in the future.

Wrangler v2 introduces module system

Wrangler v2 introduces a module system for both modules and service worker format Workers.

Wrangler v4 esbuild upgrade from v0.17.19 to v0.24

Wrangler v4 upgrades esbuild from v0.17.19 to v0.24. This brings improvements such as the ability to use the `using` keyword with RPC. Dynamic wildcard imports like `import('./data/' + kind + '.json')` now automatically include all matching files in the bundle, which may result in unwanted files being bundled. Going forward, Wrangler will periodically update the esbuild version included with Wrangler, and since esbuild is a pre-1.0.0 tool, this may sometimes include breaking changes to how bundling works, potentially in Wrangler minor versions.

wranglerjs-compat-webpack-plugin for custom webpack builds

For Workers projects using webpack with custom code transforms or modifications beyond loaders, the wranglerjs-compat-webpack-plugin package can reproduce Wrangler v1's build steps in Wrangler v2. This plugin is a port of the wrangler-js functionality that was included in Wrangler v1. Install it as a devDependency alongside webpack@^4.46.0 and webpack-cli, then add it to the webpack.config.js plugins array.

Webpack build script in package.json

After adding wranglerjs-compat-webpack-plugin to a webpack configuration, add a build script to package.json with the value 'webpack'.

Migrate webpack projects from Wrangler v1 to v2

Wrangler v2 no longer supports the `type` and `webpack_config` keys in the Wrangler configuration file. Developers using webpack must update their configuration depending on their use case: those using `[build]` to run webpack externally can continue unchanged, those using `type = webpack` without custom configuration should remove that key, those using webpack for JSX/TypeScript/WebAssembly support should remove `type` and `webpack_config` keys and rely on Wrangler v2's built-in support, and those using custom webpack configuration for code transforms should migrate to an external `[build]` process or maintain a custom webpack setup with the wranglerjs-compat-webpack-plugin.

wranglerjs-compat-webpack-plugin usage in webpack.config.js

Example of configuring wranglerjs-compat-webpack-plugin in webpack.config.js: const { WranglerJsCompatWebpackPlugin, } = require('wranglerjs-compat-webpack-plugin'); module.exports = { // ... plugins: [new WranglerJsCompatWebpackPlugin()], };

Wrangler v2 built-in support for TypeScript, JSX, WebAssembly

Wrangler v2 has built-in support for TypeScript, JSX, WebAssembly, and HTML files. The Workers runtime handles JSX and TypeScript natively. When using Wrangler v2, developers can import any modules they need and the Workers runtime automatically includes them in the built Worker, eliminating the need for a custom webpack configuration for these file types.

wranglerjs-compat-webpack-plugin npm installation example

Install wranglerjs-compat-webpack-plugin and related dependencies as devDependencies with: npm install --save-dev webpack@^4.46.0 webpack-cli wranglerjs-compat-webpack-plugin

Module fetch handler signature in Wrangler v1

A Module Worker fetch handler has the signature: async fetch(request, env, ctx) where request is the same as event.request from service worker format, waitUntil() and passThroughOnException() are accessible from ctx instead of event, and env contains bindings like KV namespaces, Durable Object namespaces, Config variables, and Secrets.

build.upload.rules in Wrangler v1 modules

The rules field in build.upload is optional and defines an ordered list of rules for module type handling. Each rule requires: type (required) - the module type such as ESModule, CommonJS, Text, Data, CompiledWasm; globs (required) - UNIX-style glob rules matching module relative path from build.upload.dir without ./ prefix; fallthrough (optional) - if true, allows further rules for this module type, if false or unspecified, further rules are ignored.

Default build.upload.rules in Wrangler v1

Default rules for modules format are implicit and do not need to be included in configuration. The defaults are: ESModule type matching **/*.mjs globs, and CommonJS type matching **/*.js and **/*.cjs globs. These defaults are treated as the last two rules in the list.

Service Worker deprecation in Wrangler v1

Service Workers are deprecated but still supported in Wrangler v1. Cloudflare recommends using Module Workers instead. New features may not be supported for Service Workers.

CommonJS shim for modules format in Wrangler v1

If your project is written using CommonJS modules, you need to re-export your handlers and Durable Object classes using an ES module shim. Refer to the modules-webpack-commonjs template as an example.

package.json main field for service-worker format in Wrangler v1

When using service-worker format, ensure the main field in your package.json references the Worker you want to publish.

Module format in Wrangler v1 Workers

Module Workers export their event handlers instead of using addEventListener calls. Module Workers receive all bindings (KV Namespaces, Environment Variables, and Secrets) as arguments to the exported handlers. With the Service Worker format, these bindings are available as global variables. Modules may import other uploaded ES Modules, and CommonJS modules may require other uploaded CommonJS modules.

build field in Wrangler v1 configuration

The build field is top-level only and optional. It configures a custom build step to be run by Wrangler when building your Worker. It supports both service-worker and modules formats with different configurations for each.

build command field in Wrangler v1

The command field in the build configuration is optional. It specifies the command used to build your Worker. On Linux and macOS, it is executed in the sh shell; on Windows, it is executed in the cmd shell. Shell operators && and || may be used.

build cwd field in Wrangler v1

The cwd field in the build configuration is optional. It specifies the working directory for commands and defaults to the project root directory.

build watch_dir field in Wrangler v1

The watch_dir field in the build configuration is optional. It specifies the directory to watch for changes while using wrangler dev and defaults to the src directory relative to the project root directory.

build.upload format field for service-worker in Wrangler v1

For service-worker format Workers, the format field in build.upload is required and must be set to "service-worker". Service Workers use addEventListener and look like: addEventListener("fetch", (event) => { event.respondWith(new Response("I'm a service Worker!")); });

build.upload configuration for modules format in Wrangler v1

For modules format Workers, the build.upload configuration requires: format (required) set to "modules", main (required) - the relative path of the main module from dir including the ./ prefix, dir (optional, defaults to dist relative to project root) - the directory to upload modules from, and rules (optional) - an ordered list of rules defining which modules to import and their type.

Wrangler webpack integration default configuration

Wrangler includes webpack@4 by default and uses a sensible default webpack configuration. The default configuration sets target to 'webworker' and entry to './index.js', which is inferred from the 'main' field in package.json. When 'main' is undefined or missing, it defaults to index.js. The target is set to 'webworker' because Cloudflare Workers match the Service Worker API specification.

Wrangler webpack version and alternatives

Wrangler includes webpack@4. To use webpack@5 or another bundler like esbuild or Rollup, you must set up custom builds in the Wrangler file. Custom builds are configured via the 'build' option in the Wrangler configuration.

Custom webpack configuration must set target to webworker

When bringing your own webpack configuration file, you must always set the 'target' option to 'webworker' in your webpack configuration. This is required because Cloudflare Workers are built to match the Service Worker API.

Webpack configuration for Workers Sites with context

When using webpack with Workers Sites, ensure your webpack configuration sets the 'context' option appropriately. If webpack.config.js is in a subdirectory (like workers-site), set 'context' to __dirname to ensure entry and context paths are resolved correctly relative to the webpack.config.js file location, not the project root where wrangler commands are run.

Using webpack ProvidePlugin to shim globals

You can use webpack's ProvidePlugin to replace global APIs with third-party implementations. Import the webpack module and add a 'plugins' array to your webpack configuration with a new webpack.ProvidePlugin instance. Pass an object where keys are the global names to replace and values are the module names to use as replacements. For example: new webpack.ProvidePlugin({ URL: "url-polyfill" }) replaces the URL global with the url-polyfill npm package.

Wrangler v1 backwards compatibility webpack_config warning

Wrangler v1.6.0 and earlier automatically loaded webpack.config.js from the project root. Versions after v1.6.0 require you to explicitly specify the 'webpack_config' field in your Wrangler file. When upgrading from wrangler@1.6.0 or earlier, add 'webpack_config = "webpack.config.js"' to your Wrangler file to resolve webpack configuration warnings.

Avoid eval in webpack devtool for Workers

When configuring webpack devtool for Workers development, avoid using 'eval' or 'eval'-based source maps because the Workers environment does not allow the eval function. Use alternatives like 'cheap-module-source-map' for development builds.

Give your agent this brain