-
-
Notifications
You must be signed in to change notification settings - Fork 20
Description
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:
-
Using
lazy: truein the CommonJS transform plugin- Added
@babel/plugin-transform-modules-commonjswithlazy: trueoption - Failed because TypeScript's compiler has its own export hoisting behavior
- Added
-
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
-
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:
- Identifies export statements at the top of the file
- Removes them from their original position
- 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