DEV Community

Luca
Luca

Posted on

One line blanked our whole React app: Vite manualChunks and the temporal dead zone

I build Candidate Falcon, a practice site for hiring assessments and one-way video interviews. At the start of November a release that added two new interview types reached production, and every page went blank. The login form didn't render, no button worked, and the console showed one error:

ReferenceError: Cannot access 'ko' before initialization
Enter fullscreen mode Exit fullscreen mode

It stayed broken for about 11 hours, partly because our deploy checks said everything was fine. This post is about why one innocent-looking line caused it, and the two checks we added so it can't happen quietly again.

The setup: manual chunks

The app is built with Vite, and the Rollup output uses manualChunks to split the bundle by area of the site:

manualChunks(id) {
  const normalizedId = id.replace(/\\/g, '/');

  if (normalizedId.includes('/node_modules/')) return 'vendor';
  if (includesAny(normalizedId, ONE_WAY_CHUNK_MATCHERS)) return 'one-way';
  if (includesAny(normalizedId, TIPS_CHUNK_MATCHERS)) return 'tips';
  if (includesAny(normalizedId, HOME_CHUNK_MATCHERS)) return 'home';
},
Enter fullscreen mode Exit fullscreen mode

Everything under src/pages/prep/video-interviews/ goes into a chunk called one-way. Code in that folder imports shared modules that stay in the main chunk, such as @/lib/videoProviders. And the main chunk imports the one-way chunk. So the two chunks import each other.

That cycle doesn't exist in the source. videoProviders.ts imports nothing from the video-interview folder. The cycle only appears once Rollup groups modules into chunks: chunk A holds modules that need chunk B, and chunk B holds modules that need chunk A.

The line that broke it

A file inside the video-interview folder kept its own hard-coded list of valid providers. The release added two providers, so it replaced the copy with the shared constant, to have one source of truth:

+import { VIDEO_PROVIDER_IDS } from "@/lib/videoProviders";

-const VALID_PROVIDERS: OneWayProvider[] = ["hirevue", "sparkhire", "vidcruiter", "talview"];
+const VALID_PROVIDERS: readonly OneWayProvider[] = VIDEO_PROVIDER_IDS;
Enter fullscreen mode Exit fullscreen mode

It looks like a textbook cleanup.

Here's what happens when the browser loads the bundle. ES modules in a cycle are evaluated in a fixed order. When the main chunk starts, it first evaluates the chunks it imports, including one-way. one-way imports from the main chunk, but the main chunk is already in progress, so the browser doesn't wait for it and runs the body of one-way straight away. That body now contains const VALID_PROVIDERS = VIDEO_PROVIDER_IDS, and VIDEO_PROVIDER_IDS is a const in the main chunk whose declaration hasn't run yet.

Reading a let or const binding before its declaration has run throws a ReferenceError: the binding is in its temporal dead zone. ko is simply what the minifier called VIDEO_PROVIDER_IDS. The error was thrown while the bundle was first being evaluated, so the main chunk never finished, and nothing after it ran, including React rendering the app.

The hard-coded array had no imports, so it was always safe. Reading the shared constant inside a function would have been safe too: by the time any function runs, both chunks have finished evaluating. The bug wasn't importing the value. It was reading it while the module was still loading.

Why nothing caught it

  • The dev server doesn't build chunks. Vite serves each module separately in development, so there's no chunk cycle and the modules load in their natural order. The bug only exists in the production bundle.
  • Unit tests import modules directly, so the same is true there.
  • Our deploy check used curl. Our pages are prerendered, so every URL returned 200 with the right title and content. The HTML was fine. The JavaScript that makes it interactive crashed on load.

The fix

Read the value when it's needed, not when the module loads:

// Read VIDEO_PROVIDER_IDS when called, never into a module-level constant: this file is in the 'one-way' chunk
// and @/lib/videoProviders in the main one, which import each other, so a top-level read runs before the main
// chunk has set the value.
const isValidProvider = (value: string): value is OneWayProvider =>
  (VIDEO_PROVIDER_IDS as readonly string[]).includes(value);
Enter fullscreen mode Exit fullscreen mode

isValidProvider is defined at module level, but it only touches VIDEO_PROVIDER_IDS when it's called.

Guard 1: a test for the pattern

Testing chunk evaluation order in Vitest isn't practical, but we can ban the pattern that triggers it. This test walks the folder that becomes the one-way chunk, collects the names each file imports from outside it, and fails if any of them is copied into a module-level constant:

const root = join(__dirname, '..', 'src', 'pages', 'prep', 'video-interviews');

/** Names imported as values from modules outside the video-interviews folder. */
const outsideImports = (source: string) =>
  [...source.matchAll(/import\s+\{([^}]*)\}\s+from\s+["'](@\/(?!pages\/prep\/video-interviews)[^"']+)["']/g)].flatMap(([, names]) =>
    names
      .split(',')
      .map((name) => name.trim())
      .filter((name) => name && !name.startsWith('type '))
      .map((name) => name.split(/\s+as\s+/).pop()!.trim()),
  );

it('never copies a value imported from outside the chunk into a module-level constant', () => {
  const offenders: string[] = [];
  for (const file of walk(root)) {
    const source = readFileSync(file, 'utf8');
    for (const name of outsideImports(source)) {
      const alias = new RegExp(`^(?:export\\s+)?const\\s+\\w+(?::[^=]+)?\\s*=\\s*${name}\\s*;`, 'm');
      if (alias.test(source)) offenders.push(`${relative(root, file)}: ${name}`);
    }
  }
  expect(offenders).toEqual([]);
});
Enter fullscreen mode Exit fullscreen mode

It's a regex, so it only catches the simple alias case (const X = importedValue;), not every possible top-level read. It would have caught this one, and it documents the rule right where the next person would trip over it.

Guard 2: check the real site in a real browser

After every deploy we now open the live site in a browser and read the console on the login page, the homepage and one page that changed. To reproduce chunk problems locally, build for production and serve the output:

npx vite build
npx vite preview
Enter fullscreen mode Exit fullscreen mode

vite preview serves the same chunks as production, which is the only place this kind of bug exists.

Takeaways

  • manualChunks can create import cycles between chunks that don't exist between your modules.
  • Inside such a cycle, a module-level read of an imported const can run before that const is initialized. Reads inside functions are safe.
  • If your HTML is prerendered, a 200 with the right title proves nothing about your JavaScript. Check the console.

I wrote this with the help of an AI assistant, working from the project's commits and code. The snippets come from the repository, trimmed for length.

Top comments (1)

Collapse
 
mosmox_studio profile image
Mosmox Studio •

The curl-based deploy check is the scariest part, and it's very common with prerendered sites. Besides banning the pattern, you could also break the chunk cycle itself: put the shared modules that one-way imports (like @/lib/videoProviders) into their own chunk that imports nothing back from page chunks. Rollup then evaluates it first, and module-level reads are safe again.