Skip to content

Design: Import defer #21

Open
Open

Description

@IWANABETHATGUY

RFC: Import defer

Summary

The TC39 proposal Deferring Module Evaluation adds import defer * as ns from './x' and import.defer('./x'). A deferred import loads and links a module graph, but the module evaluates only when code uses its namespace.

Today Rolldown accepts the syntax, but it removes the defer phase and evaluates the module eagerly. This RFC proposes to keep the deferred evaluation in the bundled output, behind a new option experimental.importDefer.

The design has three goals:

  1. The bundled output keeps the semantics of the proposal, also with code splitting, cycles, top-level await and tree shaking.
  2. The output passes 95% or more of the test262 tests for import defer. The implementation passes 243 of 252 tests (96.4%).
  3. A build without the option has no cost. Its output does not change. Its build time does not increase measurably.

Basic example

Input:

// src/main.js
import defer * as chart from './chart.js';

console.log('start');

export function draw(data) {
  // The first access evaluates chart.js and scale.js.
  return chart.render(data);
}

export function getChart() {
  // An escaping use gets the deferred namespace object.
  return chart;
}
// src/chart.js
import { scale } from './scale.js';

console.log('chart evaluated');

export function render(data) {
  return data.map(scale);
}
// src/scale.js
console.log('scale evaluated');

export const scale = (x) => x * 2;

Config:

export default {
  input: 'src/main.js',
  experimental: { importDefer: true },
};

Output (without the runtime helpers):

// src/scale.js
var scale;
// src/chart.js
var chart_exports = /* @__PURE__ */ __exportAll({ render: () => render });
var chart_deferred = /* @__PURE__ */ __deferNs(() => (init_chart(), chart_exports), chart_exports);
function render(data) {
  return data.map(scale);
}
function init_chart() {
  return (init_chart = __esmMin(() => {
    // src/scale.js
    console.log('scale evaluated');
    scale = (x) => x * 2;
    // src/chart.js
    console.log('chart evaluated');
  }))();
}
// src/main.js
console.log('start');
function draw(data) {
  return (init_chart(), render)(data);
}
function getChart() {
  return chart_deferred;
}
export { draw, getChart };
  • init_chart() holds the top-level code of chart.js and scale.js. The first call evaluates the two modules. A later call returns at once, or throws the error of the first call again.
  • scale.js has no init wrapper of its own. Only chart.js imports it, so its code is in the init wrapper of chart.js (see "Deferred groups").
  • The static access chart.render becomes (init_chart(), render).
  • getChart() uses the namespace as a value, so it returns chart_deferred. This object is a Proxy. Its traps evaluate the module at the operations that the proposal specifies (see "Semantics").

This script imports a build and shows the order of the logs:

const mod = await import('./dist/main.js');
console.log('imported');
console.log(mod.draw([1, 2]));
const ns = mod.getChart();
console.log(Object.prototype.toString.call(ns), Object.keys(ns));
Build Logs
Rolldown today (the option is off) scale evaluated, chart evaluated, start, imported, [ 2, 4 ], [object Module] [ 'render' ]
Rolldown with experimental.importDefer start, imported, scale evaluated, chart evaluated, [ 2, 4 ], [object Deferred Module] [ 'render' ]
Node.js 26.8.1 with --js-defer-import-eval, no bundler The same logs as the row above

Motivation

An app often evaluates code at startup that the first request or the first page does not use. A server app pays this cost at each cold start. A large client app pays it before the first interaction.

A dynamic import() delays this code, but each use then becomes asynchronous, so the API of the caller changes. A lazy require() call also delays code and keeps the API synchronous, but only CommonJS code can call it directly. In Node.js, an ES module must first get a require function from createRequire(). import defer keeps a synchronous API. The module loads with its importer, and it evaluates only at the first use of its namespace.

Today Rolldown removes the defer phase and shows this warning:

import defer is currently lowered to a normal import. This changes execution timing because side effects run immediately instead of when the deferred import is first used.

The deferred module then evaluates at startup, and the app gets no benefit.

Users cannot keep import defer in the output either. Node.js 24.12.0 and 26.8.1 cannot parse it without the V8 flag --js-defer-import-eval. With the flag, Node.js 26.8.1 runs the static form, but import.defer() stops V8 with a fatal error. Thus a bundler must change the syntax into code that these runtimes can run. webpack and Rspack do this behind experiments.deferImport. Rolldown and Vite have no such option.

A bench with open-source packages shows the possible gain. The bench is a Hono app for workerd. Its core is eager. The entry imports each of the four routes with import defer * as.

The results:

Build Startup, Node.js Startup, workerd First use of all 4 routes Startup + all 4 routes Size
Rolldown, no import defer 35.8 ms 59.4 ms 0 ms 35.8 ms 1,391,118 B
Rolldown + import defer 19.5 ms (−46%) 20.1 ms (−66%) 18.3 ms 38.0 ms (+6%) 1,394,736 B (+0.26%)
webpack 5.112.2, no import defer 36.4 ms 59.0 ms 0 ms 36.5 ms 1,414,291 B
webpack 5.112.2 + import defer 19.0 ms 20.5 ms 21.2 ms 40.5 ms 1,426,390 B
Method, and the first use of each route
  • Each build is one minified file (codeSplitting: false, platform: 'neutral'). webpack uses terser.
  • Node.js 26.8.1 (V8 14.6): vm.SourceTextModule compiles and evaluates the file. Each sample uses a new process. Each build gets 2 warm-up samples, then 30 samples. The values are medians.
  • "First use" is the time to read the default export of the deferred namespace of a route, after startup. This read evaluates the route and its deferred closure.
  • workerd: the value is the time until await mf.ready in Miniflare, minus the time of an empty Worker. The values are medians of 30 samples.
  • The bench is a composite of packages, not a real app. The adoption strategy has a step for measurements on real apps.
Route Rolldown, first use webpack, first use
/ai 8.4 ms 8.8 ms
/graphql 6.2 ms 6.2 ms
/s3/* 3.4 ms 3.0 ms
/ssr 1.1 ms 3.5 ms

Detailed design

Terms

This example shows all terms:

// main.js
import defer * as ns from './x.js';

console.log('start');
console.log(ns.then); // undefined: not a trigger, so x.js does not evaluate
console.log(ns.foo); // 1: a static access and a trigger, so y.js and x.js evaluate here
globalThis.saved = ns; // an escaping use: the code uses ns as a value
// x.js
import './y.js';

console.log('x evaluated');
export const foo = 1;
// y.js
console.log('y evaluated');

The logs are start, undefined, y evaluated, x evaluated and 1. Node.js 26.8.1 with --js-defer-import-eval gives the same logs.

  • Deferred import: import defer * as ns from './x' or import.defer('./x'). In the example: the first line of main.js.
  • Defer target: the module that a deferred import names. In the example: x.js.
  • Deferred closure: a defer target and each module that it imports statically, directly or through other modules. In the example: x.js and y.js.
  • Deferred namespace: the object that a deferred import gives. In the example: ns.
  • Evaluate: run the top-level code of a module. In the example, x.js evaluates at ns.foo, and then console.log('x evaluated') runs.
  • Trigger: an operation on a deferred namespace that evaluates the defer target. The section "Semantics" lists these operations. In the example: ns.foo. ns.then is not a trigger.
  • Static access: a member expression on ns with a known key. In the example: ns.then and ns.foo.
  • Escaping use: a use of ns as a value. In the example: globalThis.saved = ns.
  • Init wrapper: the function init_x() that holds the top-level code of the module x. In the example output below: init_x().

Output (without the runtime helpers):

// x.js
var x_exports = /* @__PURE__ */ __exportAll({ foo: () => 1 });
var x_deferred = /* @__PURE__ */ __deferNs(() => (init_x(), x_exports), x_exports);
function init_x() {
  return (init_x = __esmMin(() => {
    // y.js
    console.log('y evaluated');
    // x.js
    console.log('x evaluated');
  }))();
}
// main.js
console.log('start');
console.log(void 0);
console.log((init_x(), 1));
globalThis.saved = x_deferred;
  • The static access ns.then becomes void 0, and ns.foo becomes (init_x(), 1).
  • The escaping use reads x_deferred, the Proxy of the deferred namespace.
  • init_x() also holds the code of y.js, because only x.js imports y.js (see "Deferred groups").

User guide

Options

interface InputOptions {
  experimental?: {
    /** @default false */
    importDefer?: boolean;
  };
  checks?: {
    /** @default true */
    deferredExternalEvaluatedEagerly?: boolean;
  };
}
  • experimental.importDefer turns the feature on. When the option is off, Rolldown removes the defer phase and warns with UNSUPPORTED_FEATURE, as before. The warning now names the option.
  • checks.deferredExternalEvaluatedEagerly turns the warning DEFERRED_EXTERNAL_EVALUATED_EAGERLY on or off.

Semantics

The output follows these rules of the proposal. The rules come from the spec text and its test262 tests. Where V8 does not follow the spec, the output follows the spec (see "Prior art").

  1. A static deferred import loads and links the module, but does not evaluate it. Only the namespace form import defer * as ns is valid.
  2. These operations on ns evaluate the module synchronously: [[Get]], [[HasProperty]], [[GetOwnProperty]], [[DefineOwnProperty]] and [[Delete]] with a string key, and [[OwnPropertyKeys]]. For example: ns.foo, 'foo' in ns, delete ns.foo and Object.keys(ns). The key does not have to be an export.
  3. These operations do not evaluate the module: any Symbol key, the key "then", [[Set]], [[GetPrototypeOf]], [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]] and private names. ns.then is always undefined.
  4. The deferred namespace has a null prototype, is not extensible, and has Symbol.toStringTag equal to "Deferred Module". Each export looks like a data property (writable: true, configurable: false).
  5. One module has one deferred namespace. Each deferred import of the module, static or dynamic, from any file, gives the same object. This object is different from the eager namespace.
  6. If another import of the module is eager, the module evaluates at the position of that eager import.
  7. The modules with top-level await in the deferred closure evaluate eagerly, at the position of the deferred import. If the defer target itself has top-level await, it evaluates eagerly too. import.defer() resolves after these modules finish.
  8. A trigger throws a TypeError when the module or one of its dependencies has the state "evaluating" or "evaluating-async", or is a member of a cycle that did not finish. Then the trigger evaluates no module.

import.defer()

import() loads a module and evaluates it before its promise resolves. import.defer('./x') loads the chunk of x and the chunks that x needs, but it does not evaluate x. It resolves to the deferred namespace of x, and x evaluates at the first trigger, as for the static form.

Thus code can load a chunk early, for example when the page is idle, and evaluate it only when the user needs it:

// src/main.js
// Load the chunk early. table.js does not evaluate.
export const tablePromise = import.defer('./table.js');

export async function showTable() {
  const table = await tablePromise;
  return table.rows();
}
// src/table.js
console.log('table evaluated');

export function rows() {
  return [1, 2, 3];
}

This script imports the build, waits until the chunk of table.js loads, and then calls showTable():

const { showTable, tablePromise } = await import('./dist/main.js');
await tablePromise; // The chunk of table.js has loaded.
console.log('before showTable');
console.log(await showTable());
main.js uses Logs
import('./table.js') table evaluated, before showTable, [ 1, 2, 3 ]
import.defer('./table.js') before showTable, table evaluated, [ 1, 2, 3 ]

Output with import.defer() (without the runtime helpers):

// src/main.js
const tablePromise = (async (n) => ((n = await import('./table-Bi-d4Afw.js')), n.table_deferred))();
async function showTable() {
  return (await tablePromise).rows();
}
export { showTable, tablePromise };
// src/table.js
var table_exports = /* @__PURE__ */ __exportAll({ rows: () => rows });
var table_deferred = /* @__PURE__ */ __deferNs(() => (init_table(), table_exports), table_exports);
function rows() {
  return [1, 2, 3];
}
function init_table() {
  return (init_table = __esmMin(() => {
    console.log('table evaluated');
  }))();
}
export { init_table, rows, table_deferred, table_exports };
  • The output loads the chunk with a normal import(). The code of table.js is inside init_table(), so the load does not evaluate table.js.
  • The chunk exports table_deferred, the deferred namespace of table.js. import.defer() resolves to this object.
  • table.rows() is the first trigger. The Proxy calls init_table(), and table.js evaluates.
  • This output uses output.minifyInternalExports: false. The option changes only the names of the exports that Rolldown adds for other chunks. With the default (true for ESM output), the chunk has export { table_deferred as n, table_exports as r, rows, init_table as t }, and main.js reads n.n.
  • The specifier must be a string literal. For another expression (import.defer(expr)), Rolldown uses import(expr) and warns with UNSUPPORTED_FEATURE. The module then evaluates when it loads.
  • The output code for import.defer() has no .then call, because the test262 test promise-prototype-then-not-called.js patches Promise.prototype.then.

Output formats and externals

Case ESM output CommonJS output IIFE and UMD output
A module in the bundle Deferred evaluation Deferred evaluation Deferred evaluation
An external module, static import defer The output keeps import defer * as ns from "ext" A deferred namespace with a lazy require("ext") Warning UNSUPPORTED_FEATURE. The global evaluates eagerly.
An external module, import.defer() The output keeps import.defer("ext") (async () => __deferNsCached("ext", () => __toESMCached("ext", require("ext"))))() Warning. A native import().
An external module that a module of a deferred closure imports eagerly Eager. Warning DEFERRED_EXTERNAL_EVALUATED_EAGERLY. A lazy require("ext") in the init wrapper of the importer Eager. Warning.
  • ESM output keeps import defer and import.defer() for an external module. Thus the target runtime must support import defer. Node.js 26.8.1 parses it only with --js-defer-import-eval, and workerd cannot parse it today.
  • Rolldown does not check the target yet, because Oxc has no target data for import defer (see "Future work"). Rolldown also keeps the import attributes of an external import without a target check. Rspack also keeps import defer for an external module. webpack fails the build, unless the user sets output.environment.deferImport.
  • Rolldown warns when a module of a deferred closure imports an external module eagerly. ESM output loads each external module at the start of the chunk, so the external module evaluates when its chunk loads. IIFE and UMD output get external modules as globals or as wrapper arguments, so they cannot delay them either. CommonJS output can delay the require().
  • Rolldown does not give this warning in these cases:
    • The external module is a builtin module.
    • The external module has no side effects.
    • A module outside the deferred closures, in the same chunk, also imports the external module.
  • The warning gives two solutions: bundle the dependency, or use CommonJS output when the runtime and the dependency support require().

Plugin hooks

The plugin API does not change. The resolveId hook gets no phase. An import defer shares one resolveId call with an import of the same specifier, and an import.defer() shares one call with an import(). The reason is in the spec: it compares only the specifier and the import attributes of two module requests (ModuleRequestsKeyEqual). Thus both imports must get the same module. With the phase, a plugin could resolve them to two different modules.

Tree shaking

  • A static access keeps only the exports that it reads.
  • An escaping deferred namespace keeps all exports, as an escaping eager namespace does.
  • Tree shaking removes a defer target that has no side effects and no uses.
  • The statement ns.foo; keeps the trigger, unless the deferred closure has no side effects.

Tree shaking can keep more modules than in a build without import defer, in two cases:

  • A module that only re-exports other modules stays in the output when a deferred module imports a binding through it.
  • With code splitting (the default) or with more than one entry, the target of an export * in a deferred module stays in the output, also when no code uses it. In a build with one chunk, the export * statement stays only when it has side effects or a used binding.

Dev mode

The bundled dev mode (experimental.devMode) has no HMR support for import defer yet. In dev mode, Rolldown turns experimental.importDefer off. Each deferred import becomes a normal import, and a warning names dev mode.

The unbundled dev server of Vite is out of scope. It sends each module as it is, so there import defer can work only in a browser with native support.

Known limits

  • A module of a deferred closure evaluates inside its init wrapper. Thus typeof arguments gives "object", not "undefined". Direct eval code also runs in this function: eval("new.target") gives undefined and does not throw a SyntaxError. output.strictExecutionOrder and the __esm wrapper of esbuild give the same results.
  • Async sibling modules evaluate one after the other, not concurrently. Thus the evaluation of async modules, also in cycles, follows the spec only approximately. Code that relies on concurrency can break: for example, a module that waits for a promise that a later sibling resolves never finishes. This is the general rule of Rolldown for top-level await, also without import defer (see Top Level Await in the Rolldown docs). The preparation of a deferred import uses the same rule: it awaits the modules with top-level await one after the other.
  • The check for a module that is still evaluating (see "Semantics") sees only cycles through imports. It does not see a cycle through a global variable. webpack has the same gap.
  • Without preserveModules, a later import can evaluate before a deferred module in the same chunk. Native ESM evaluates the deferred module first. Two cases are known. In the first, an earlier import enters an import cycle that contains the deferred module. In the second, the importer reads a binding of the deferred module through a re-export module with no side effects. With strictExecutionOrder, both cases give the native order.
  • An import.defer() of a CommonJS module evaluates the module at once. The proposal does not cover CommonJS modules.
  • main has a gap that also affects import defer, and the gap needs a separate fix on main. When tree shaking removes a re-export, its target can evaluate later than in native ESM. This occurs when the target has no side effects and is in a different chunk. Because of this gap, with code splitting or with more than one entry, the target of an export * in a deferred module stays in the output, also when no code uses it (see "Tree shaking").
All known limits
  • CommonJS: the importers with no wrapper in one chunk share one deferred namespace for each CommonJS module and interop mode. An importer of each kind below gets its own deferred namespace:

    • an importer with a wrapper, for example a module of a deferred closure
    • each importer with strictExecutionOrder
    • an importer in another chunk
    • an importer with another interop mode: a .mjs importer and a .js importer read default differently

    The eager namespace has the same limits for wrappers, for strictExecutionOrder and for chunks. An external module in CommonJS output has one deferred namespace for each interop mode. A CommonJS entry module in CommonJS, IIFE or UMD output gets no entry facade.

  • A deferred namespace with no static list of keys (see "The deferred namespace") copies its keys at the first trigger that reaches its Proxy. Until then, the namespace is extensible, so Object.isExtensible(ns) gives true. A static access such as ns.foo does not reach the Proxy, so the module can evaluate before the copy. After Object.preventExtensions(ns), the first trigger that reaches the Proxy, for example Object.keys(ns), throws a TypeError if the namespace has keys. An empty namespace has no keys to copy, so Object.keys(ns) gives []. The reason: a Proxy reports "not extensible" only when its target is not extensible, and the target needs all keys before that.

  • With preserveModules, a user-defined entry module that is also a defer target evaluates when it loads. The reason: its entry facade needs a second file for the module.

  • With preserveModules and ESM output, the file of a CommonJS module in a deferred closure evaluates the module when the file loads (export default require_x(); at its end). A deferred import loads the file, so the module evaluates before the first access. CommonJS output evaluates the module at the first access.

  • Some eager importers of a deferred module x in another chunk are not eligible for the init after the import (see "import.defer() and code splitting"). Such an importer calls init_x() in its body. Thus x evaluates after the later imports of the chunk of the importer, but native ESM evaluates x before them. This occurs more often without preserveModules, because a chunk then has more than one module. A deferred module in a common chunk has the same order for each eager importer in another chunk.

  • External modules in CommonJS output must load with require(). An ES module with top-level await cannot load that way (ERR_REQUIRE_ASYNC_MODULE on Node.js 24.12.0).

  • import.defer("ext", options) in CommonJS output keeps the native import() and evaluates the module at once, because require() cannot carry import attributes.

  • The warning DEFERRED_EXTERNAL_EVALUATED_EAGERLY has a known false positive: a module of a deferred closure that also has an eager importer counts as deferred. It also has a known false negative. A module that only an inlined import() reaches (IIFE, UMD, codeSplitting: false) counts as eager, so the warning does not show.

  • We did not check import defer with experimental.onDemandWrapping, or the CommonJS carrier of output.strictExecutionOrder for a deferred import.

  • With the option on, the runtime chunk can export __toESM with no user.

  • The closure of an import.defer() target gets init wrappers, also when an eager import evaluates the closure first.

  • Deferred groups: the sourcemap lists the source of a grouped module two times in sources, but the mappings are correct. Some moved statements have no mappings. Without minify, the code in a group wrapper has no indent. The default minify: 'dce-only' prints the chunk again with the correct indent.

Diagnostics

Code Kind When
UNSUPPORTED_FEATURE Warning The option is off, or dev mode is on. Also for a non-literal import.defer(expr), and for a deferred external module in IIFE or UMD output.
DEFERRED_EXTERNAL_EVALUATED_EAGERLY Warning A module of a deferred closure imports an external module eagerly, in ESM, IIFE or UMD output

Implementation

Init wrappers and module order

Rolldown already uses a lazy ESM wrapper (__esm and __esmMin), for example for a require() of an ES module and for output.strictExecutionOrder. The feature uses this wrapper. The code of each module of a deferred closure runs in an init wrapper: in its own wrapper, or in the wrapper of its group (see "Deferred groups"). The whole closure needs wrappers, because a trigger evaluates the dependencies of the target first. Thus a dependency can evaluate before its eager position.

A deferred wrapper is a hoisted function:

function init_x() {
  return (init_x = __esmMin(() => {
    // The top-level code of x.js
  }))();
}

A call can come before the declaration in these cases:

  • through a module cycle;
  • through a chunk cycle with an acyclic module graph;
  • during a pause at a top-level await.

With a var init_x = __esmMin(...) declaration, the assignment does not run before such a call, and the call throws TypeError: init_x is not a function.

In the module sort, Rolldown visits the eager imports of a module first, then its deferred imports. Thus the declarations of a deferred closure come before the body of the importer. The init calls evaluate the modules. A module with an eager import still evaluates at its eager position.

Static access

The finalizer (the step that rewrites the code of each module) rewrites each static access, so the deferred namespace is necessary only for an escaping use.

Input Output
ns.foo (an export) (init_x(), foo)
ns.bar (not an export) (init_x(), void 0)
ns.then void 0 (no call)
ns.foo = v, delete ns.foo A write or a delete on the deferred namespace

After the first call, a call of init_x only checks a flag. In the bench, a static read after evaluation took 1.4 ns. The webpack form, a getter that replaces itself, took 10.2 ns.

The deferred namespace

__deferNs(init, ns) returns a Proxy:

  • The target of the Proxy has a null prototype, one data property for each export except "then", in sorted order, and Symbol.toStringTag: "Deferred Module". The target is not extensible.
  • At a trigger, the traps evaluate the module. Then they read the values from the eager namespace ns, so live bindings work.
  • A CommonJS module and a module with dynamic exports (an export * from CommonJS or from an external module) have no static list of keys. The helper copies the keys after the module evaluates, as webpack does. It copies them at the first trigger that reaches the Proxy. Until then, the target is extensible (see "Known limits").
  • Each ES module that is a defer target has one deferred namespace, in the chunk of the target. For a CommonJS module, the importers with no wrapper in one chunk share one deferred namespace for each interop mode. Each other deferred import of a CommonJS module gets its own deferred namespace. An external module in CommonJS output has one deferred namespace for each interop mode, in all chunks (see "Known limits").

Example:

import defer * as ns from './x.js'; // x.js: export const foo = 1;

Object.isExtensible(ns); // false. x.js does not evaluate.
Object.keys(ns); // x.js evaluates. ['foo']
Object.getOwnPropertyDescriptor(ns, 'foo'); // { value: 1, writable: true, enumerable: true, configurable: false }

The data properties of the target are only placeholders. The placeholders are necessary because of the invariants of Proxy. The deferred namespace is not extensible, so its target is not extensible either. Then the ownKeys trap can report only the keys of the target. The getOwnPropertyDescriptor trap can report a non-configurable property only when the target has it. Without the placeholders, a report of an export by these traps throws a TypeError.

A CommonJS module is already lazy (__commonJS). A deferred import of a CommonJS module becomes:

var import_x,
  x_deferred = /* @__PURE__ */ __deferNs(() => import_x || (import_x = __toESM(require_x())));

A static access loads the module at the root of the member chain, (import_x || (import_x = __toESM(require_x()))).fn(). Thus a method call gets the eager namespace as this, as in the eager build.

Evaluation state

A trigger must throw a TypeError when the module or one of its dependencies has the state "evaluating" or "evaluating-async", or is a member of a cycle that did not finish. __esmMin cannot implement this check. A call while the module evaluates returns, and it does not throw. The check needs the state of each module that can be on the stack at a trigger.

Only some modules get a state record. We call them tracked modules. The edges of the graph for this check are the import, import defer and import.defer() records between the ES modules of the deferred closures. A module is a tracked module when it is a member of a strongly connected component of this graph, and one of these conditions is true:

  • The component has a cycle with a defer target.
  • A member has top-level await, or depends on a module with top-level await.

A tracked module uses __esmState. A trigger on a tracked module calls the ready check __esmDefer(init_x), which implements the spec ReadyForSyncExecution. For a target that is not tracked, no module of its closure can be on the evaluation stack at a trigger. Thus the ready check cannot fail, and a trigger calls init_x directly.

An example shows the ready check. In the example, a.js and b.js import each other. a.js also defers b.js and reads b.x in its body. main.js imports a.js, and it also defers b.js.

flowchart TB
    main[main.js] -- import --> a
    main -. import defer .-> b
    subgraph tracked [tracked modules]
        a[a.js] -- import --> b[b.js]
        b -- import --> a
        a -. import defer .-> b
    end
Loading

main.js and a.js also import log.js. It exports a log array and a function read(access), which calls access and returns 'ok' or 'TypeError'. a.js and b.js are tracked modules, because their cycle contains the defer target b.js. The output for a.js:

function init_a() {
  return (init_a = __esmState(
    () => {
      init_b(init_a);
      init_log();
      log.push('a reads b: ' + read(() => (__esmDefer(init_b), 1)));
    },
    () => [init_b],
  ))(arguments[0]);
}

At run time, the calls run in this order:

sequenceDiagram
    participant main as main.js
    participant a as a.js
    participant b as b.js
    main->>a: init_a()
    Note over a: "evaluating"
    a->>b: init_b(init_a)
    Note over b: "evaluating"<br/>b.js imports a.js, which is on the stack,<br/>so a.js is the cycle root of b.js
    Note over b: the body of b.js runs
    b-->>a: return. b.js stays "evaluating",<br/>because its cycle root did not finish
    Note over a: the body of a.js runs
    a->>b: b.x: __esmDefer(init_b)
    b-->>a: TypeError
    Note over a,b: the body of a.js ends.<br/>a.js and b.js become "evaluated"
    a-->>main: return
    main->>b: b.x: __esmDefer(init_b)
    b-->>main: 1
Loading

The read in the body of a.js throws a TypeError, because the cycle root a.js did not finish. A later read in main.js gives the value. The log is ['a reads b: TypeError', 'later b: ok'].

  • The record keeps the state (not started, evaluating, evaluating-async, evaluated, error), the error, the cycle root, and the DFS indices of the spec InnerModuleEvaluation.
  • At run time, __esmState follows the steps of InnerModuleEvaluation. It pushes each record to a stack, finds the cycle root, and gives each member of the cycle its cycle root. When a body throws, each member of the cycle gets the error.
  • A failed module throws its error again at each later call, as __esm does today.

Top-level await

The modules with top-level await in a deferred closure evaluate eagerly, at the position of the deferred import. At this position, the importer prepares the closure.

Example: main.js defers d.js, and d.js imports a.js, which has top-level await.

// src/main.js
import defer * as d from './d.js';

console.log('main');

export const read = () => d.x;
// src/d.js
import './a.js';

console.log('d');

export const x = [1];
// src/a.js
console.log('a start');
await 0;
console.log('a end');

The output of main.js:

__esmGather(init_d) || (await __esmGather());
console.log('main');
const read = () => (__esmDefer(init_d), x);

The logs are a start, a end and main. Thus a.js evaluates before the code of main.js, but d.js does not evaluate. A later read() logs d and returns [1]. d.js is a tracked module, because it depends on a module with top-level await. Thus the access calls the ready check __esmDefer(init_d) (see "Evaluation state").

  • The first call, __esmGather(init_d), walks the state records at run time, as the spec GatherAsynchronousTransitiveDependencies does. It returns true when the importer has nothing to await. When the importer has an init wrapper, the call also gets it: __esmGather(init_d, init_i).
  • The second call awaits the async modules that the walk found.
  • After the preparation, a trigger evaluates the closure synchronously. An async module body awaits a dependency only when the dependency did not finish. For example, the body of d.js starts with __esmDepDone(init_a(init_d), init_a, init_d) || await init_a(init_d).

The walk runs at run time, because a static list cannot skip a branch. In this graph, E failed before the deferred import:

flowchart LR
    I[importer] -. import defer .-> D
    D -- import --> E["E (failed before)"]
    D -- import --> X
    E -- import --> A["A (top-level await)"]
    X -- import --> A
Loading

The walk skips E, but it reaches A through X, so the importer awaits A. Without the edge from X to A, the walk does not reach A, and A does not evaluate. A static list cannot tell these two cases apart, because the state of E is known only at run time.

import.defer() and code splitting

  • import.defer('./x') is a chunk root, like import('./x'). The chunk of x must not evaluate x when it loads. Thus the dynamic entry chunk of x does not call init_x() at its end.
  • An eager importer of x in another chunk must call init_x(). A call in the body of the importer runs after all imports of its chunk, so import './x.js'; import './y.js' would evaluate y before x. Thus the chunk of an eligible importer calls init_x() right after its import of the chunk of x. In ESM output, the chunk imports a small init chunk that calls init_x(). In CommonJS output, the chunk calls init_x() right after the require(). An importer is eligible when all of these conditions are true:
    • The importer is the first module of its chunk that runs code.
    • Each earlier import of the importer evaluates while the chunk loads. For example, these earlier imports evaluate in the body of the chunk: a module in the same chunk, a CommonJS module in CommonJS output, and a deferred module with top-level await.
    • The chunk of x does not import the chunk of the importer.
  • An importer that is not eligible calls init_x() in its body (see "All known limits").
  • Plugins see the init chunk as any other chunk: renderChunk gets it, and the imports of the importer list it.
  • For code splitting, a static import defer is a static edge. The target goes into a chunk that loads with the importer, because a trigger must evaluate it synchronously.
  • When an import.defer() target is in the chunk of the importer, the declarations of the target and of its deferred closure come first in the chunk. Thus a call before them cannot read undefined.

External modules in CommonJS output

  • A deferred import of an external module becomes var import_ext, ext_deferred = __deferNsCached("ext", () => import_ext || (import_ext = __toESMCached("ext", require("ext")))).
  • __toESMCached keeps one eager namespace for each external file name and interop mode. Thus all chunks share one object.
  • __deferNsCached keeps one deferred namespace for each external file name and interop mode in the same way. import.defer("ext") gets the same object.
  • An eager import of an external module in a deferred closure moves into the init wrapper of its importer, so the external module loads at the first trigger.

Deferred groups

Without groups, each module of a deferred closure has its own init wrapper. Each wrapper costs time at startup (the engine parses the function) and at the first use (the engine compiles and calls it). A deferred group is a root and its members, with one init wrapper:

  • A root is a module of a deferred closure that keeps its own init wrapper.
  • A member is a module that only one root reaches through plain import edges, in the same chunk, and that no other code calls.
  • The member bodies run in the wrapper of the root, in the order of evaluation. The declarations of the members stay at the top level of the chunk, because code outside the group can read them.
  • These modules keep their own wrappers: a defer target, a tracked module, a module with top-level await, an entry module, a module that eager code reaches, and a module whose wrapper another chunk imports. A require() edge does not make a member, because a require() can run conditionally.
  • A CommonJS module that only one group uses moves into the wrapper of the root. Then the engine compiles it at the first use, not at startup. In the bench (60 samples), startup plus one route becomes 0.2 to 0.5 ms faster for 3 routes, and 0.2 ms slower for /ssr.
  • There are no groups with output.strictExecutionOrder, dev mode, output.generatedCode.profilerNames, inline common chunks, or a non-ESM output format.

Example: the Basic example with one more module, format.js. main.js and chart.js both import it.

// src/main.js
import defer * as chart from './chart.js';
import { format } from './format.js';

export const draw = (data) => format(chart.render(data));
// src/chart.js
import { scale } from './scale.js';
import { format } from './format.js';

console.log('chart evaluated');

export const render = (data) => format(data.map(scale));
// src/format.js
console.log('format evaluated');

export const format = (v) => String(v);
flowchart LR
    main[main.js] -. import defer .-> chart
    main -- import --> format["format.js (own wrapper)"]
    subgraph group [deferred group]
        chart["chart.js (root)"] -- import --> scale["scale.js (member)"]
    end
    chart -- import --> format
Loading
  • chart.js is a root, because it is a defer target.
  • scale.js is a member. Only chart.js reaches it, through a plain import.
  • format.js keeps its own wrapper, because the eager code of main.js reaches it.

The output:

// src/format.js
var format;
function init_format() {
  return (init_format = __esmMin(() => {
    console.log('format evaluated');
    format = (v) => String(v);
  }))();
}
// src/scale.js
var scale;
// src/chart.js
var render;
function init_chart() {
  return (init_chart = __esmMin(() => {
    // src/scale.js
    console.log('scale evaluated');
    scale = (x) => x * 2;
    // src/chart.js
    init_format();
    console.log('chart evaluated');
    render = (data) => format(data.map(scale));
  }))();
}
// src/main.js
init_format();
const draw = (data) => format((init_chart(), render)(data));
export { draw };

The declaration var scale stays at the top level of the chunk. Only the body of scale.js moves into init_chart. main.js calls init_format() at its eager position, so format evaluated logs at startup.

In the bench (60 samples, against the same build without groups), the groups reduce the init wrappers from 546 to 33. Startup becomes 0.62 ms faster, and the first use of all routes becomes 2.38 ms faster.

PIFE on deferred wrappers

A PIFE is a function expression in parentheses. V8 compiles such a function eagerly. optimization.pifeForModuleWrappers makes the function of each module wrapper a PIFE. Its default is true, except for platform: 'neutral'.

Without PIFE, a deferred wrapper is:

function init_x() {
  return (init_x = __esmMin(() => {
    // The top-level code of x.js
  }))();
}

With PIFE, the inner function is in parentheses:

function init_x() {
  return (init_x = __esmMin((() => {
    // The top-level code of x.js
  })))();
}

The other code blocks in this RFC do not show these parentheses.

The function of a deferred wrapper is a PIFE on all platforms by default. On a deferred wrapper, the PIFE makes V8 compile nothing at startup, because the inner function is inside the hoisted function init_x(). V8 compiles init_x only at its first call, and the inner function runs right after that. An explicit pifeForModuleWrappers: false turns off PIFE on deferred wrappers too.

Step Without PIFE With PIFE
Startup V8 does not compile init_x V8 does not compile init_x
First call of init_x V8 compiles init_x V8 compiles init_x and the inner function
__esmMin calls the inner function V8 compiles the inner function No compile step

In the bench, import defer makes the startup faster without PIFE, and PIFE then makes the first use faster. The values are medians of 30 samples on Node.js, from the same run as the table in "Motivation". The two import defer builds come before the other startup changes, so they are slower than the final build.

Build Startup First use of all 4 routes
No import defer 35.8 ms 0 ms
import defer, no PIFE 22.1 ms 28.8 ms
import defer, with PIFE 21.0 ms 20.6 ms

With JavaScriptCore (Bun 1.4.2), the effect of PIFE was not measurable.

No cost without the option

  • The scanner sets one flag for each module during the existing scan. There is no new pass.
  • Each new branch in the link stage and the generate stage reads this flag, or the option, first.
  • The defer runtime helpers are in their own file. The runtime includes this file only when the option is on.
  • The existing snapshot tests give the same output without the option. Only the text of the old warning and the CLI help change.
  • We counted the instructions of three benchmarks without the option: threejs, rome_ts and multi-duplicated-top-level-symbol. An early version of the implementation gave −0.19%, −0.08% and +0.12% against main (minimums). The later startup changes (PIFE on deferred wrappers, the export * rule, fewer empty init wrappers and the deferred groups) gave −0.04%, −0.10% and +0.02% against the version before them (medians). We did not count the fixes between these two versions. These values are in the noise.
  • There is a known small cost: 9 new LinkingMetadata fields (about 140 B for each module) and 13 more DependedRuntimeHelperMap slots (312 B for each module). The measurements do not show it.

Tests

  • A new test262 runner runs the 252 import defer tests of the pinned test262 commit. 243 pass (96.4%). This runner cannot pass the 4 tests that need sloppy mode (see the failures below).
  • There are 119 fixtures for the feature. 111 of them also run the output and check the result.
The 9 test262 failures
  • The 4 tests syntax/valid/nested-with-*-import-defer-*.js use with, which needs sloppy mode. The runner gives each test to Rolldown as a .js entry, and Rolldown parses a .js file as module code, which is strict. In a manual run with a .cjs entry and CommonJS output, all 4 tests pass.
  • errors/resolution-error/import-defer-of-missing-module-fails.js: Rolldown reports an unresolved import as a build error, so a bundle cannot reject at run time.
  • evaluation-top-level-await/async-cycle-dependency-of-deferred-module and evaluation-top-level-await/flattening-order need concurrent evaluation of async sibling modules. Rolldown evaluates async sibling modules one after the other, also without import defer (see "Known limits"). webpack passes flattening-order, because its runtime for async modules evaluates siblings concurrently.
  • evaluation-triggers/ignore-private-name-access.js: Node.js 24.12.0 and 26.8.1 do not implement nonextensible-applies-to-private. This is a failure of the engine, not of the bundler.
  • promise-prototype-then-not-called: a native import() on Node.js 24.12.0 calls Promise.prototype.then 4 times for a plain module. A build with one chunk calls it 0 times.

Drawbacks

  • Complexity. The feature changes the scanner, the link stage, the generate stage, the finalizer, the renderer and the runtime. It also changes the shared crates, one builtin plugin, the NAPI binding, the TypeScript API and the code generator. The runtime code for top-level await and for the evaluation state follows the spec steps closely. A change to this code needs the test262 suite and the fixtures.
  • Size. The init wrappers and their calls add bytes. In the bench, the output is 0.26% larger than without import defer. Some increase is unavoidable, because the delayed code needs a wrapper function, and the runtime needs the defer helpers. Can be improved later: fewer init wrappers, and no init wrapper for an empty module (see "Future work").
  • Semantic limits. Some limits remain: the arguments and eval limit, async sibling modules that evaluate one after the other, and CommonJS modules (see "Known limits"). The order of async sibling modules is the general rule of Rolldown for top-level await, also without import defer. Can be fixed later: the arguments limit (an option that rewrites free arguments reads). Concurrent evaluation of async sibling modules needs a change of the general rule for all builds. See "Future work" for both. The eval limit and the CommonJS limit have no planned fix.
  • Tree shaking. Tree shaking can keep more modules than without import defer, in the two cases of "Tree shaking". Can be fixed later: a route past a re-export module (see "Future work"), and the separate fix of the gap across chunks on main (see "Known limits"). After that fix, tree shaking can also remove an unused target of an export * with code splitting.
  • Dev mode. The bundled dev mode does not support import defer yet. Dev builds evaluate the deferred modules eagerly, so they behave differently from production builds. Can be fixed later: HMR for import defer in the bundled dev mode (see "Future work"). It is the first step before the option becomes stable (see "Adoption strategy").

Alternatives

A module registry, as in webpack

webpack keeps each deferred module as a factory in its module registry. It does not concatenate a deferred module into its importer, but it can concatenate the deferred module with its eager dependencies inside the factory.

This form also delays the evaluation, and the startup gain is about the same. In the bench, the startup in Node.js goes from 36.4 ms to 19.0 ms with webpack, and from 35.8 ms to 19.5 ms with Rolldown. This design does not use the form, because the form costs more:

  • A factory has its own scope. Thus an importer outside the factory reads each export through a getter. An init wrapper keeps the bindings in the scope of the chunk, so an importer reads them directly. A read after evaluation took 10.2 ns with the webpack form, against 1.4 ns.
  • import defer added 12,099 B (+0.86%) to the webpack bundle, against 3,618 B (+0.26%) to the Rolldown bundle.
  • Startup + all 4 routes was 4.0 ms (+11%) slower than the eager build with webpack, against 2.2 ms (+6%) with Rolldown.

The size and the time numbers compare each import defer build with the eager build of the same tool, because the two tools also differ in other ways, for example the minifier. The read compares the two forms on one small case.

With this design, import defer adds less to the output than with webpack: +0.26% against +0.86%. It also adds less time when all 4 routes run: +6% against +11% over the eager build. The startup gain is about the same: −46% against −48% in Node.js, and −66% against −65% in workerd.

The core design of Rolldown is static linking: Rolldown binds each import at build time and scope-hoists the modules into chunks. It adds runtime helpers only where a feature needs them. This design keeps that core: it uses the lazy ESM wrapper that Rolldown already has, and it adds a few runtime helpers. The code of a deferred closure stays scope-hoisted with the rest of the chunk. The webpack form needs a second module model in the output: a registry of factories next to the scope-hoisted code. Thus a change to the webpack form is not worth its cost.

Prior art

  • The TC39 proposal, and its test262 tests.
  • V8 has the flag --js-defer-import-eval. With the flag, Node.js 26.8.1 runs the static form, but import.defer() stops V8 with a fatal error. The static form does not follow the spec in 2 cases:
    • A module of the deferred closure already started, and it waits for top-level await. The spec makes the importer wait for that module, so the access works. V8 runs the importer at once, and the access throws a TypeError.
    • The deferred module failed earlier, and one of its dependencies has top-level await. The spec does not start that dependency. V8 starts it.
  • webpack 5.112.2 has experiments.deferImport (default false). Each deferred module stays a factory in the module registry. A static access uses a getter that replaces itself. An escaping use gets a Proxy, with one cached object for each module and mode. The ready check of webpack uses an evaluating flag on each module and the members of the static strongly connected component. A deferred import of an external module fails the build, unless the user sets output.environment.deferImport.
  • Rspack 2.3.1 has experiments.deferImport too. Its helper has no identity cache and no cycle check. It keeps import defer for an external module in ESM output.
  • Rollup parses phase: 'defer', but treats it as an eager import (rollup/rollup#5932).
  • TypeScript: microsoft/TypeScript#60757.
The test262 suite on Rolldown, webpack and Rspack

All three tools ran with the same runner, Node.js 26.8.1 and test262 bd21f3a3dd. Config for webpack and Rspack: mode: 'production', minimize: false, mangleExports: false, target: 'node24', ESM output, experiments.deferImport: true.

Tool Passed
Rolldown (an early version of the branch) 241/252
webpack 5.112.2 241/252
Rspack 2.3.1 202/252
  • This run used the runner before a fix of the harness (the defines: list of a harness file). The fix added 2 passes for Rolldown (243). We did not run webpack and Rspack again, so their numbers can also be higher now.
  • 9 tests failed in all 3 tools: the 2 tests of the harness gap, the 4 nested-with-* tests, import-defer-of-missing-module-fails.js, ignore-private-name-access.js and promise-prototype-then-not-called.js.
  • webpack fails defer-import-after-evaluation.js and import-defer-does-not-evaluate.js, which Rolldown passes. Rolldown fails async-cycle-dependency-of-deferred-module and flattening-order, which webpack passes.
  • Rspack has 41 more failures. Examples: trigger tests that do not evaluate, ignore-* tests that evaluate, build errors for cycle and top-level await cases, and the identity test.

Some cases outside test262:

Case Rolldown webpack Rspack
Static dep.then, no then export undefined, no evaluation (.js and .mjs input) .js input (javascript/auto): a warning, and the module evaluates. .mjs input (javascript/esm): build error Build error (.js and .mjs input)
Two files and import.defer() give one object Yes Yes No
Read of self.x in a self-import cycle TypeError TypeError No error
ESM external module, default options The output keeps import defer, and Node.js fails to parse it Build error The output keeps import defer, and Node.js fails to parse it

Adoption strategy

  • The feature is opt-in through experimental.importDefer. It is not a breaking change: without the option, the output does not change.
  • Vite has no option of its own in the first version. A Vite user sets build.rolldownOptions.experimental.importDefer. We did not test import defer in a Vite build yet.
  • These steps come before the option becomes stable:
    1. The bundled dev mode with HMR. This step removes the fallback of dev mode.
    2. The Vite build: import.defer() gets the same preload as import(), and the dynamic import variables plugin supports import.defer(`./x/${y}.js`).
    3. Docs: a user page, a section in the Vite build guide, and the limit of the unbundled dev server.
    4. Measurements on open-source apps: change the eager imports that the startup path does not use to import defer, and measure the startup and the build time.
  • After these steps, importDefer can become the default. Before that, the option and its behavior can change.

Unresolved questions

  1. Which conditions make importDefer the default?
  2. In Node.js, the startup is still 0.5 ms slower than with webpack (19.5 ms against 19.0 ms). One possible cause is in Oxc: in minify mode, oxc_codegen prints a string as a template literal when the two forms have the same length. In the bench, a copy of an earlier build with double-quoted strings in these places started 0.33 to 0.53 ms faster. That build came before the deferred groups and the other startup changes. Thus this result does not show how much of the final 0.5 ms gap the strings cause. Do we propose a change to Oxc?

Future work

  • HMR for import defer in the bundled dev mode.
  • The Vite build integration (preload and dynamic import variables).
  • Fewer wrappers: no init wrapper for a module of a deferred closure that each deferred importer already evaluates eagerly first.
  • Tree shaking: route past a re-export module to the module that owns the binding (measured: about 100 B in the bench), and no init wrapper for an empty module.
  • Tree shaking of unread deferred imports: an unread deferred import can keep the wrapper of its target, though nothing calls it.
  • A target check for ESM output: a warning for a deferred external module when the target does not support import defer. This needs target data for import defer in Oxc.
  • In ESM output, import defer for an external module that a deferred closure imports eagerly, when the target supports it. Then the external module evaluates with its importer, as in CommonJS output.
  • An option to rewrite free arguments reads in wrapped modules. output.strictExecutionOrder can use it too.
  • Move the new LinkingMetadata fields behind one Option<Box<_>>, to remove the memory cost without the option.
  • Outside import defer: concurrent evaluation of async sibling modules. This changes the general rule of Rolldown for top-level await in all builds, so it needs its own design. The 2 test262 failures in evaluation-top-level-await need it.

Activity

  1. hyfdev commented on Nov 12, 2026

    @hyfdev
    Member

    Is "experimental" option required? I feel like we don't need to publish it with experimental option.

  2. IWANABETHATGUY commented on Nov 12, 2026

    @IWANABETHATGUY
    MemberAuthor

    Is "experimental" option required? I feel like we don't need to publish it with experimental option.

    1. In import defer we need to consider at least follow scenario:

    The dimensions

    ┌───────────────┬────────────────────────────────────────────────────────────────────────┬───────┐
    │   Dimension   │                                 Values                                 │ Count │
    ├───────────────┼────────────────────────────────────────────────────────────────────────┼───────┤
    │ Form          │ import defer * as ns, import.defer()                                   │ 2     │
    ├───────────────┼────────────────────────────────────────────────────────────────────────┼───────┤
    │ Target        │ ESM, CommonJS, JSON                                                    │ 3     │
    ├───────────────┼────────────────────────────────────────────────────────────────────────┼───────┤
    │ Use           │ static access ns.x, escape (ns as a value)                             │ 2     │
    ├───────────────┼────────────────────────────────────────────────────────────────────────┼───────┤
    │ Cycle         │ none, read while the target evaluates (TypeError), cycle that finished │ 3     │
    ├───────────────┼────────────────────────────────────────────────────────────────────────┼───────┤
    │ External      │ none, the target, inside the deferred closure                          │ 3     │
    ├───────────────┼────────────────────────────────────────────────────────────────────────┼───────┤
    │ Output format │ ESM, CJS, IIFE/UMD                                                     │ 3     │
    └───────────────┴────────────────────────────────────────────────────────────────────────┴───────┘
    

    2 × 3 × 2 × 3 × 3 × 3 = 324 combinations.

    I followed the approach used for previous complex features, make the feature opt-in behind an experimental option so we can ship it sooner while continuing to validate it.

    1. Webpack and Rspack also make this feature opt-in.

    2. I reviewed the implementation and ran a few fuzzing rounds, but I can’t guarantee it’s bug-free. I’d prefer to keep it opt-in for now. I’m open to shipping it without a flag if that’s what most of the team prefers, though we may need more time to validate it.

  3. sapphi-red commented on Nov 13, 2026

    @sapphi-red
    Member

    Would adding the experimental option make the bugs related to import defer not to "leak" for the other places? If not, I think there's not much reason to add the option. import defer support can be marked as experimental without the option.

    experimental.importDeferExternal

    I think we don't need this option. For external + ESM output, I think we can keep import defer * as ns from "ext" regardless of the option, aligning with how import attributes handle the similar case. If we want to add warnings or transform it to static imports, I think we should respect the transform.target or add an option to output.generatedCode.

    An external module that a module of a deferred closure imports eagerly

    Would you show me an example code for this?

    The resolveId hook gets extraOptions.phase, with the value 'evaluation' or 'defer'. An eager import and a deferred import of the same specifier get two separate resolveId calls. this.resolve() always resolves in the 'evaluation' phase.

    I'm not sure about this. import defer and normal import should resolve to the same module per spec. If there isn't a huge reason to do so, I think it's better not to let plugins return different values depending on the phase.

  4. IWANABETHATGUY commented on Nov 16, 2026

    @IWANABETHATGUY
    MemberAuthor

    Would adding the experimental option make the bugs related to import defer not to "leak" for the other places?

    Yes. With the option off, the output is the same as main (no snapshot changes) and the build time stays in the noise. The only exception is a fix for top-level await through an import cycle, which I'll send to main first as a separate PR.

    For external + ESM output, I think we can keep import defer * as ns from "ext" regardless of the option

    Agreed. I'll remove importDeferExternal and the IMPORT_DEFER_EXTERNAL error, so that ESM output keeps import defer * as ns from "ext" when importDefer is on. When it's off, the output stays the same as main (a normal import with a warning). I won't add a target warning for now.

    Would you show me an example code for this?

    // main.js
    import defer * as chart from './chart.js';
    console.log('main start');
    console.log(chart.render(2));
    
    // chart.js
    import { format } from 'ext'; // external
    console.log('chart evaluated');
    export function render(x) { return format(x); }

    In Node.js with --js-defer-import-eval, ext evaluates when chart.render is accessed, after main start. In ESM output, import { format } from "ext" is at the top of the chunk, so ext evaluates before main start. webpack does the same, also with output.environment.deferImport, but without a warning. In CJS output, Rolldown and webpack both load ext with require() when chart.js evaluates, so the order matches Node.js.

    This is a known limitation of ESM output: an external import evaluates when its chunk loads (also without import defer), so Rolldown warns with DEFERRED_EXTERNAL_EVALUATED_EAGERLY.

    import defer and normal import should resolve to the same module per spec.

    Agreed. I'll remove phase from the resolveId options and from the resolve dedupe key, so an import and a deferred import of the same specifier share one resolveId call, as on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions