1 RN Thing a Day – Day 3: What Is Babel
Ola Abaza

Ola Abaza @ola_1313

Joined:
Aug 8, 2024

1 RN Thing a Day – Day 3: What Is Babel

Publish Date: Aug 7
0 0

What Is Babel?
JavaScript compiler that lets you use modern JavaScript features (like optional chaining ?., nullish coalescing ??, arrow functions, etc.) and compiles them down to code that older browsers or environments can understand.

What Babel Does

let, const, arrow functions --> Older var and function syntax
JSX (Hello) --> React.createElement() calls
Optional chaining (a?.b) --> Compatible fallback code
Nullish coalescing (a ?? b) --> Equivalent old JS logic
TypeScript or Flow --> Stripped out, leaving only JS

Babel in React Native
React Native uses Babel under the hood to:

  • Compile JSX
  • Support modern JavaScript features
  • Work across Android/iOS JavaScript runtimes
  • Enable developer tools (like source maps, plugins)

What is babel.config.js?
babel.config.js is Babel’s configuration file. It tells Babel:

  • Which plugins to use (e.g. babel-plugin-lodash)
  • Which presets to use (e.g. @babel/preset-env, metro-react-native-babel-preset in React Native)
// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: ['lodash'],
};
Enter fullscreen mode Exit fullscreen mode

Babel Plugins:
Plugins extend Babel’s capabilities. For example:

  • @babel/plugin-proposal-optional-chaining → allows a?.b
  • babel-plugin-lodash → optimizes lodash imports
  • @babel/plugin-transform-runtime → reduces bundle size

Babel Presets:
Presets in Babel are collections of plugins bundled together for convenience.

Instead of manually listing all the Babel plugins needed to transform your code, you just use a preset.

Examples of Common Presets:

  • @babel/preset-env --> Transforms modern JavaScript (ES6+) into code that works in older browsers
  • @babel/preset-react --> Adds support for JSX and React features
  • @babel/preset-typescript --> Transforms TypeScript into JavaScript
  • module:metro-react-native-babel-preset --> Used in React Native projects; supports JSX, modern JS, etc.

When Does Babel Run?
In React Native, when you run npx react-native start (Metro bundler watches and transpiles files using Babel)

Example Flow (React Native)

  1. You write modern JavaScript (optional chaining, ES6 imports, etc.)
  2. Metro + Babel transforms it to compatible code (require(), if (a && a.b))
  3. The transformed bundle is sent to the device or emulator
  4. The JS runs in the JavaScript engine (Hermes or JSC)

Why It Matters

  • Babel is not included in the final app — it’s a dev/build tool.
  • Babel ensures cross-platform compatibility by converting newer JS to older syntax.
  • It enables advanced features like JSX, decorators, and custom plugins.

Comments 0 total

    Add comment