Skip to content

Cannot access 'pageInterpolatorCube' before initialization #37

@krvns

Description

@krvns

This "fix" contains scripts related to the build process.

fix-exports.js

Purpose

Fixes the "exports before definition" issue in CommonJS compiled output.

The Problem

When using TypeScript with named exports of functions, the CommonJS compilation often places exports at the top of the file, before the actual function definitions:

// Original TypeScript
export function myFunction() { /* ... */ }

// Compiled to CommonJS (problematic)
exports.myFunction = myFunction;  // ❌ Reference to myFunction before it's defined!
function myFunction() { /* ... */ }

This causes runtime errors in JavaScript environments with the error message:

TypeError: Cannot access 'myFunction' before initialization

Attempted Solutions

We tried several approaches with Babel configuration before settling on this post-build script:

  1. Using lazy: true in the CommonJS transform plugin

    • Added @babel/plugin-transform-modules-commonjs with lazy: true option
    • Failed because TypeScript's compiler has its own export hoisting behavior
  2. Custom Babel presets and plugins

    • Tried configuring TypeScript to handle generics, enums, etc.
    • Required numerous packages and complex configuration
    • Ended up with many dependency conflicts with React Native's Babel preset
  3. Modifying react-native-builder-bob configuration

    • Attempted to customize how Bob builds the files
    • Couldn't properly override the TypeScript/Babel pipeline

Proposed Solution

The fix-exports.js script runs after the build process and:

  1. Identifies export statements at the top of the file
  2. Removes them from their original position
  3. Adds them back at the end of the file, after all function definitions

This approach:

  • Is far more reliable than Babel configuration
  • Requires no additional dependencies
  • Works with any future changes to the TypeScript compiler or Babel

Usage

The script is automatically called in the build command in package.json:

"scripts": {
  "build": "bob build && node ./scripts/fix-exports.js"
}

If you can fix this in a better way, please help. Otherwise feel free to use this script as a post package install band-aid

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions