babel/babel · error

Cannot load preset ${name} relative to ${dirname} in a brows

Error message

Cannot load preset ${name} relative to ${dirname} in a browser

What it means

Symmetric to loadPlugin, the browser build's loadPreset stub throws 'Cannot load preset ${name} relative to ${dirname} in a browser'. resolvePreset returns null in the browser, so any preset referenced by string name triggers this error when the loader attempts to load the module from disk, which is impossible in a browser environment.

Source

Thrown at packages/babel-core/src/config/files/index-browser.ts:112

  name: string,
  dirname: string,
): Handler<{
  filepath: string;
  value: unknown;
}> {
  throw new Error(
    `Cannot load plugin ${name} relative to ${dirname} in a browser`,
  );
}

export function loadPreset(
  name: string,
  dirname: string,
): Handler<{
  filepath: string;
  value: unknown;
}> {
  throw new Error(
    `Cannot load preset ${name} relative to ${dirname} in a browser`,
  );
}

View on GitHub (pinned to 06b6eae39d)

Solutions

  1. Import the preset as a function in the browser and reference it directly: presets: [require('@babel/preset-env')].
  2. Use @babel/standalone, which exposes preset-env and others by string name out of the box.
  3. Resolve presets at build time (Node) and inject the preset functions into the browser bundle.

Example fix

// before - throws error 33 in browser
babel.transform(code, { presets: ['@babel/preset-env'] });

// after - use standalone
import * as babel from '@babel/standalone';
babel.transform(code, { presets: ['env'] });
Defensive patterns

Strategy: validation

Validate before calling

const isBrowser = typeof window !== 'undefined';
if (isBrowser) {
  opts.presets = (opts.presets || []).map(p =>
    typeof p === 'string' ? require(p) : p
  );
}

Type guard

function isPresetFunction(value: unknown): boolean {
  return typeof value === 'function' || (Array.isArray(value) && typeof value[0] === 'function');
}

Try / catch

try { babel.transform(code, opts); }
catch (err) {
  if (/Cannot load preset .* in a browser/.test(err.message)) {
    console.error('Import the preset function instead of using a string name');
  }
  throw err;
}

Prevention

When it happens

Trigger: A browser-bundled Babel transform whose options include `presets: ['@babel/preset-env']` or any string preset name, rather than passing an already-imported preset function.

Common situations: Using @babel/core (not standalone) in browser code with string preset names; config object shared across Node and browser where Node resolves presets by name from node_modules.

Related errors


AI-assisted analysis of babel/babel@06b6eae39d (2026-08-03). Data as JSON: /data/errors/a478923221c86895.json. Report an issue: GitHub.