Chuyển đến nội dung

Bài 20 · Native Modules and APIs

Writing Your Own Native Module

Build a local Expo native module with the Expo Modules API in Swift and Kotlin, expose functions, constants, events and views to TypeScript, and test the JS side with a mock.

Expo's SDK covers the common device features, but sooner or later you need something it does not: a vendor's hardware SDK, a platform API with no wrapper, or a performance-critical routine. The Expo Modules API lets you write that native code in Swift (iOS) and Kotlin (Android) and call it from TypeScript, without touching the C++ bridge or hand-writing Objective-C.

Native compilation is impossible in a web page, so the Swift, Kotlin and generated project files here are read-only. The live stand-ins implement the JavaScript side of the bridge so you can understand what your TypeScript code talks to.

When to write a module

Before you do, check for an existing library (the Expo SDK, the React Native directory, npm). Write your own when the feature is missing, when you must wrap a proprietary SDK, or when you need native speed. A native module forces a development build (Expo Go cannot contain your code), and you must maintain Swift and Kotlin.

flowchart LR
  TS["TypeScript<br/>MyModule.hello()"] --> J["JS wrapper<br/>requireNativeModule"]
  J --> I["iOS: Swift<br/>MyModule.swift"]
  J --> A["Android: Kotlin<br/>MyModule.kt"]
  I --> OS1["iOS APIs"]
  A --> OS2["Android APIs"]

One JavaScript interface, two native implementations.

Create a local module

Local modules live in your own project, in the modules/ folder:

Terminal
npx create-expo-module@latest --local

Answer the prompts (name, for example device-info). You get:

Text
modules/device-info/
  expo-module.config.json         which platforms and classes
  index.ts                        JS entry (what the app imports)
  src/DeviceInfoModule.ts         binds the native module
  ios/DeviceInfoModule.swift
  android/src/main/java/expo/modules/deviceinfo/DeviceInfoModule.kt

Because the module is part of the app, prebuild (Prebuild and Config Plugins) links it automatically, and npx expo run:android / run:ios compiles it.

The Swift side

Swift
// ios/DeviceInfoModule.swift
import ExpoModulesCore
import UIKit

public class DeviceInfoModule: Module {
  public func definition() -> ModuleDefinition {
    Name("DeviceInfo")

    Constants([
      "platform": "ios",
      "systemVersion": UIDevice.current.systemVersion
    ])

    Function("batteryLevel") { () -> Float in
      UIDevice.current.isBatteryMonitoringEnabled = true
      return UIDevice.current.batteryLevel
    }

    AsyncFunction("sum") { (numbers: [Double]) -> Double in
      numbers.reduce(0, +)
    }

    Events("onLowBattery")
  }
}

The Kotlin side

Kotlin
// android/.../DeviceInfoModule.kt
package expo.modules.deviceinfo

import android.os.BatteryManager
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition

class DeviceInfoModule : Module() {
  override fun definition() = ModuleDefinition {
    Name("DeviceInfo")

    Constants("platform" to "android", "sdkInt" to android.os.Build.VERSION.SDK_INT)

    Function("batteryLevel") {
      val manager = appContext.reactContext?.getSystemService(android.content.Context.BATTERY_SERVICE) as BatteryManager
      manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) / 100f
    }

    AsyncFunction("sum") { numbers: List<Double> -> numbers.sum() }

    Events("onLowBattery")
  }
}

The definition DSL is the same on both sides:

  • Name("..."): the name JavaScript uses.
  • Constants: values available immediately.
  • Function: synchronous call (keep it fast; it blocks the JS thread).
  • AsyncFunction: returns a promise; run slow work here.
  • Events("..."): names of events native code can send with sendEvent.
  • View: exposes a native UI component (with Prop definitions).
  • OnCreate, OnDestroy, OnStartObserving, OnStopObserving: lifecycle hooks.

Argument and return types (numbers, strings, arrays, dictionaries, Record classes, enums, URLs) are converted automatically, and a wrong type produces a clear error in JavaScript.

The TypeScript side

TypeScript
// modules/device-info/src/DeviceInfoModule.ts
import { requireNativeModule, EventEmitter } from 'expo';

type DeviceInfoEvents = { onLowBattery: (e: { level: number }) => void };

declare class DeviceInfoModuleType extends EventEmitter<DeviceInfoEvents> {
  platform: string;
  batteryLevel(): number;
  sum(numbers: number[]): Promise<number>;
}

export default requireNativeModule<DeviceInfoModuleType>('DeviceInfo');
TypeScript
// modules/device-info/index.ts
import DeviceInfo from './src/DeviceInfoModule';

export const platform = DeviceInfo.platform;
export const batteryLevel = (): number => DeviceInfo.batteryLevel();
export const sum = (numbers: number[]) => DeviceInfo.sum(numbers);
export function onLowBattery(listener: (level: number) => void) {
  return DeviceInfo.addListener('onLowBattery', (e) => listener(e.level));
}

In the app: import { batteryLevel, sum } from '../modules/device-info';. Keep the public JavaScript API small and typed; hide the native names behind your own functions.

The bridge, modeled

Here is a stand-in of what requireNativeModule gives you: an object with constants, sync functions, promise-returning functions, and an event emitter. Practicing against such a fake is also how you test your JS code without a device.

JS A fake native module

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Testing the JavaScript side with a mock

Because the native object is replaced easily, unit tests (see Testing and Performance) can mock the module and check your wrapper's logic. This stand-in shows the idea with plain functions:

JS Wrapper logic against a mock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Native views

A module can also expose a native UI component:

Swift
View(MyMapView.self) {
  Prop("zoom") { (view: MyMapView, zoom: Double) in view.setZoom(zoom) }
  Events("onMarkerPress")
}

On the JavaScript side requireNativeViewManager('DeviceInfo') returns a component you wrap with typed props. Use views only when the feature is visual; most modules need functions and events only.

Publishing and alternatives

To share a module across apps, create it without --local (a standalone package with an example app) and publish it to npm. For small gaps there are alternatives: a config plugin can often enable what you need in existing native code, and Turbo Modules (React Native's own system, written in C++/Objective-C++/Java) are lower-level; the Expo Modules API is easier and works with both architectures.

Common mistakes

  • Long-running work in a synchronous Function, freezing the JavaScript thread. Use AsyncFunction.
  • Different behavior on iOS and Android because the two implementations drifted. Keep one TypeScript contract and test both.
  • Forgetting to rebuild the development build after changing Swift or Kotlin (Fast Refresh only updates JavaScript).
  • Leaking listeners: always remove event subscriptions.
  • Throwing platform-specific exceptions; convert them to Exception types with clear codes and messages.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. In which languages do you write the native part of an Expo module?

    The Expo Modules API uses Swift and Kotlin with a matching definition DSL.
  2. 2. Which definition should you use for slow work such as reading a large file?

    AsyncFunction returns a promise and keeps the JavaScript thread free.
  3. 3. Do you need a development build to use your own native module?

    Expo Go contains a fixed set of modules; custom native code needs your own build.
  4. 4. What command scaffolds a module inside your project?

    create-expo-module --local creates the template under modules/.

Summary

  • Write native code once per platform (Swift, Kotlin) with the Expo Modules API: constants, functions, async functions, events and views.
  • Bind it in TypeScript with requireNativeModule and expose a small, typed API.
  • Local modules live in modules/ and are linked by prebuild; they require a development build.
  • Inject or mock the native object to test your JavaScript wrapper.

Next: Networking and API Calls in Expo

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.