Generated banner for Expo Migrate Module
Generated logo for Expo Migrate Module

Expo Migrate Module

ExpoOfficialPublished by Expo

  • Skill
  • Workflow
  • Software development
  • MIT
  • Low risk

From the author

Migrate an existing Apple/Swift Expo native module from the Expo Modules API 1.0 definition DSL to the 2.0 macro API (sometimes called v2) while preserving its JavaScript and TypeScript contract. Use when converting or incrementally adopting @ExpoModule, @JS, @Event, @SharedObject, or @Record in an existing module. Do not use for creating a new module, general Expo SDK upgrades, or Android/Kotlin migrations.
— the description by Expo

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a systematic workflow for updating Apple/Swift Expo native modules from the legacy Expo Modules API 1.0 definition DSL to the modern 2.0 macro-based API. It emphasizes preserving the existing JavaScript and TypeScript contract, ensuring that native-side changes do not break the module's observable behavior. The process involves inventorying the current API, verifying the availability of 2.0 macro support in the target environment, and performing an incremental migration using mixed-mode development where necessary.

What it does

  • Inventories existing module exports, including functions, properties, events, and records.
  • Verifies the compatibility of 2.0 macros with the installed Expo SDK version.
  • Guides the migration of Swift code to @ExpoModule, @JS, @Event, and @Record macros.
  • Supports incremental migration through mixed-mode, keeping unsupported members in the 1.0 DSL.
  • Ensures threading and async behavior remain consistent with the original 1.0 implementation.
  • Provides a verification workflow using native unit tests and the example app.

When to use it

  • When you need to modernize an existing Apple/Swift Expo module to the 2.0 macro API.
  • When you want to adopt @ExpoModule, @JS, @Event, or @Record in a legacy module.
  • When you need to perform an incremental migration while keeping the module functional.
  • When you need to ensure that native-side changes do not alter the existing JS/TS API contract.

Advantages

  • Preserves the existing JS/TS contract, preventing breaking changes for consumers.
  • Allows for safe, incremental migration via mixed-mode development.
  • Provides clear guidance on handling threading and async behavior during migration.
  • Includes a robust verification process to ensure runtime compatibility.

Usage examples

“Migrate my existing Swift module 'CameraModule' from 1.0 DSL to 2.0 macros.”
The agent will inventory the current 'CameraModule' exports, check the installed Expo SDK version for macro support, and begin an incremental migration of the Swift classes while maintaining the existing JS interface.
“How do I handle a blocking function during my Expo module migration?”
The agent will advise on whether to keep the function in the 1.0 DSL or refactor it to use @JS(.concurrent) or other async patterns to ensure it does not block the JS thread.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/expo/expo-migrate-module/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip expo-migrate-module.zip -d .agents/skills

Documentation by Expo

Migrate an Expo Module

Migrate the Swift side of an existing Expo module without changing its observable JS API. Treat the current JS/TypeScript surface and tests as the compatibility contract. Leave Kotlin on the 1.0 DSL unless the user explicitly expands the task.

Prerequisite

Use expo 58.0.21 or newer. Earlier 58.0.x releases lack tuple conversion and the swift:check and swift:expand commands of expo-modules-cli. Older ones also lack lazy @JS properties, SharedRef<T> subclasses in @SharedObject, static shared-object members, and .withAsync, and the oldest lack closure arguments and free-form Any return values. SDK 57 also lacks .concurrent, @Union, and module auto-discovery. Do not target either. Before editing, check the installed version (npm ls expo, or the lockfile). If it is older, stop and tell the user to upgrade first.

Check the example app's own dependencies too, not only the module root. The example app is the integration surface you build and launch in step 4, so it needs the same floor.

This is a floor, not a guarantee: the macro and core surface changed in almost every 58.0.x patch release, so step 2 must still verify the installed source.

The macros are still experimental and undocumented: SDK 58 has no page about them in the Expo docs, and the API can still change under you. Say this to the user before a large migration, and prefer incremental mixed mode over converting a module wholesale.

References

  • Read references/migration-map.md before changing source. It contains the 1.0-to-2.0 mappings, semantic traps, and mixed-mode rules.

  • Read references/example.md for a full before/after walkthrough of one module through mixed mode to a complete migration. Consult it when you need to see how the per-member rules compose.

  • Read references/compatibility.md when the checked-out expo-modules-core version or branch is not known to support every requested macro. It explains how to verify the actual compile-time and runtime surface instead of guessing from a version number, gives the SDK 58 status of each capability, and shows how to run the module scanners and the expo-modules-cli checks.

Workflow

1. Establish the contract

Inspect repository instructions and the worktree before editing. Locate the Swift module classes, records, shared objects, native views, JS/TS bindings, tests, example app, podspec, expo-module.config.json, and installed or checked-out expo-modules-core.

Inventory every exported item before rewriting it:

  • module and shared-object JS names

  • function names, arity, labels, defaults, nullability, sync/async behavior, errors, and queue/thread semantics (note which AsyncFunction bodies do blocking or long-running work, any .runOnQueue(...), and sync/async pairs that share a body, such as readSync and read)

  • property names, mutability, and constant caching behavior

  • event wire names and payload shapes, including events sent with no body (1.0 sendEvent("name") sends {})

  • record field names, defaults, requiredness, and nullability

  • shared-object constructors and instance/static placement (Function vs StaticFunction/StaticAsyncFunction)

  • lifecycle hooks and views

Use the TypeScript declarations and JS call sites to resolve ambiguity. Do not silently "improve" requiredness, rename an event, or change sync behavior during a syntax migration.

2. Verify the available 2.0 surface

Inspect the macro declarations and matching core hooks in the dependency actually used by the target. Do not assume that all items in the 2.0 design are present because one macro compiles.

Classify each 1.0 item as:

  • Migrate: both its macro and required core runtime support exist.

  • Keep in DSL: mixed mode preserves it safely, or 2.0 lacks an equivalent.

  • Blocked: migration would alter the JS contract or requires unavailable runtime support.

A DSL member that takes or returns JavaScriptValue does not compile on SDK 58, so it cannot stay in the DSL. Migrate it to @JS with a borrowing JavaScriptValue parameter, as described in references/migration-map.md.

Prefer an incremental mixed-mode result over speculative generated code. Keep definition() for any remaining DSL elements; delete it only when it is empty and the resolved module name is preserved by @ExpoModule.

3. Apply the migration

Migrate one semantic group at a time: module naming, functions, properties/constants, events, shared objects, then records. Keep the diff narrow.

Follow these invariants:

  • Preserve every existing JS-visible name explicitly when Swift naming rules or macro defaults differ.

  • Keep original optional/default behavior. An optional 1.0 record field must not become required merely because 2.0 can express required fields.

  • Keep same-JS-name overloads on the DSL. The plugin does not dispatch overloads, and it reports two @JS members with one JS name on one object as a build error.

  • Preserve async threading behavior. A 1.0 AsyncFunction body ran off the JS thread; a 2.0 async @JS member starts on it and leaves only at the first await. A body that never awaits therefore blocks the JS thread, with no change to the JS signature. Audit what runs before the first await, and never leave blocking I/O on the JS actor. Fix with @JS(.concurrent), return a Task.detached from a synchronous function, or restructure onto Swift Concurrency or a continuation. A plain Task { } in a @JS function that is not nonisolated starts on the JS thread, so it does not help. Queue-pinned functions get the same treatment; .runOnQueue(.main) becomes a @MainActor async function. Merge a sync/async pair that shares a body into one function with .withAsync("name"). See the threading section in references/migration-map.md.

  • Do not use @ViewProps, @ExpoView, or @Event(sync: true). The plugin implements them, but SDK 58 core does not declare the two view macros and has no runtime support for synchronous events, so none of them builds. Keep 1.0 views on the DSL. Check the installed core for each of these instead of trusting a plugin version. references/compatibility.md has the per-capability checks.

  • Keep the OnAppContextDestroys, OnAppEntersForeground, OnAppEntersBackground, and OnAppBecomesActive components in definition(). 2.0 has no hook for them.

  • Keep the JS payload of every event. A () -> Void @Event sends undefined, but a 1.0 sendEvent("name") without a body sent {}. When JS code reads that payload, give the event an empty @Record payload type, which encodes to {}, or ask the user before you change it.

  • Keep expo-module.config.json as it is. When it has an apple.modules list (even an empty one), autolinking links only those classes. The entries are bare Swift class names, so renaming a class during migration detaches the module silently: it builds, then is absent at runtime. Without the list, autolinking links the public or open @ExpoModule classes that it finds in the package sources. It does not find a class that is still on the 1.0 DSL alone. A migrated class must stay public or open in both cases. Remove the list only when the user asks and every module class qualifies.

  • Do not change Kotlin, JS wrappers, or public .d.ts files unless the user requested an API change.

  • Never write macro-generated symbols into the module's source. The macro emits them; hand-writing or overriding them is not part of a migration.

After each group, search for old DSL entries and call sites that should have moved. Avoid broad formatting or unrelated cleanup.

When a 2.0 equivalent is missing or a group fails

When step 2 classified an item as Blocked, or a migrated group fails to build or breaks the contract, do not force it. Stop on that group and:

  1. Ask the user how to proceed for that item, with two options:

    • Co-exist: keep the item in the 1.0 definition() DSL alongside the migrated @ExpoModule (mixed mode) and continue with the other groups.

    • Revert: back out the group's edits, leaving it untouched on 1.0, and move on.

    Default to co-existence when mixed mode is verified safe, since it preserves the most progress. Revert when the half-applied change left the module in a non-building state and cannot be salvaged incrementally.

  2. Open a tracking issue on expo/expo noting the functionality that 2.0 does not yet cover, so the gap is recorded rather than silently worked around. Use gh issue create --repo expo/expo and confirm with the user before posting (per repo conventions, do not post outward-facing comments without approval). Include:

    • the 1.0 member and its JS contract

    • the specific macro or core hook that is missing (cite the evidence gap from references/compatibility.md)

    • the installed expo version, or the expo-modules-core branch when the module builds against a checkout

    Reference the issue in the handoff so the remaining DSL entry is traceable to a known limitation.

Keep going with the groups that do migrate cleanly; one blocked member does not block the rest.

4. Verify behavior

Run the narrowest available checks first, then the real integration surface:

  1. Run npx --no-install expo-modules swift:check ios from the module package root. It reports macro errors and warnings in seconds, without a build. references/compatibility.md describes it.

  2. Build or type-check the Apple module against the target expo-modules-core.

  3. Run native unit tests and JS/TS tests.

  4. Build and launch the example app when the repository provides one.

  5. Confirm that autolinking still links every module class. With an apple.modules list, each entry must match a Swift class name as it now stands. Without the list, run the scanModules check in references/compatibility.md and confirm that it reports every class as public or open. A stale entry or a missed class builds clean and fails only at runtime, so the example app must actually resolve the module, not merely compile.

  6. Compare the final exported surface with the inventory from step 1. The scanExports check in references/compatibility.md lists the JS names, parameters, and sync/async shape of every migrated member. Members that stay in the DSL are not in its output.

  7. Search for stale Name, migrated Function/AsyncFunction/StaticFunction/StaticAsyncFunction/Property/Constant/Events entries, old sendEvent calls, @Field, and duplicate registrations. Search the source you wrote, not macro expansion output.

Expansion alone is insufficient: swift:check runs only the macros, so generated code with no diagnostics can still fail to link or run against a mismatched core. If dependencies changed or macro plugin flags are missing, reinstall JS dependencies as appropriate, run the repository's CocoaPods installation workflow, and restart Xcode before diagnosing plugin communication failures.

Handoff

Never print macro-generated or core-internal symbol names to the user. references/compatibility.md cites them so you can grep for them, and the swift:expand output is full of them, but they are implementation details that change between plugin revisions, and they are noise in a report. Name a capability by its macro (@JS static, @Event(sync:)) and by observable JS behavior. Say "the installed core does not support synchronous events yet", not the name of the missing method. The exception is a tracking issue on expo/expo, where the specific missing hook is the point.

Report:

  • which members moved to 2.0

  • which members intentionally remain in the 1.0 DSL and why

  • any compatibility-sensitive choices, especially event names, record requiredness, constants, and queues

  • the commands run and any verification not completed

Submitting Feedback

If you encounter errors, misleading or outdated information in this skill, report it so Expo can improve:

npx --yes @expo/agent-cli@latest feedback --category skills --subject "expo-migrate-module" "<actionable feedback>"

Only submit when you have something specific and actionable to report. Include as much relevant context as possible. If an agent repeatedly fails at an Expo task or the user has to step in, submit a brief report of the task, expected result, and what went wrong using --category evals and the relevant Expo package or command as --subject.

Files

references/migration-map.md

1.0 to 2.0 Migration Map

Use this reference while editing. Preserve behavior first; macro adoption is secondary.

Module and naming

Convert the module class, carry the name into @ExpoModule("..."), and remove Name(...):

// 1.0
public final class CameraModule: Module {
  public func definition() -> ModuleDefinition {
    Name("Camera")
  }
}

// 2.0
@ExpoModule("Camera")
public final class CameraModule: Module {}

Always carry a custom 1.0 name into @ExpoModule("..."). Without an argument, the name defaults to the Swift class name. Core reads the @ExpoModule name only when definition() has no Name(...) entry, so a stale Name(...) silently wins in mixed mode. Remove it, then verify that the module still resolves under its expected JS name.

Keep the Module superclass. @ExpoModule also works on a class without one, but removing it is not part of a migration: sendEvent and the overridable lifecycle hooks come from it.

Functions

Move a DSL closure into a real method and use @JS("wireName") when the Swift method name is different:

// 1.0
Function("sum") { (a: Double, b: Double) -> Double in
  return a + b
}

// 2.0
@JS("sum")
func add(a: Double, b: Double) -> Double {
  return a + b
}

Preserve:

  • the JS name

  • positional arity

  • optional arguments and Swift defaults

  • thrown errors and return type

  • whether the result is synchronous or a Promise

Keep functions that resolve to the same JS name on the DSL. The plugin has no overload grouping. It reports two @JS members with one JS name on one object as a build error, so leave the overloads in definition() as they are.

Keep in DSL any unsupported signature such as variadics or unresolved generics. inout and isolated parameters are build errors. A Promise parameter is also unsupported; refactor it as described under Async functions.

These argument types work in a @JS signature on SDK 58:

  • Free-form values. Any, [Any], and [String: Any], optional or nested, are accepted as arguments, return values, and properties. A 1.0 [String: Any] argument keeps its Swift type.

  • Closures. A function-typed parameter receives the JS function. A closure that returns a value must be throws, and it blocks the caller until JS returns. A @JS function cannot return a closure. See references/compatibility.md for the rules.

  • Tuples. An unlabeled tuple such as (Int, String) converts to a JS array, and a labeled tuple such as (x: Double, y: Double) to a JS object. Replacing a 1.0 array or dictionary type with a tuple changes the Swift API, so do it only when the user asks.

  • JavaScriptValue. Take it as borrowing JavaScriptValue. On SDK 58 the DSL no longer accepts JavaScriptValue arguments or results, so such a member must migrate.

// 1.0, no longer compiles on SDK 58
Function("isFunction") { (value: JavaScriptValue) -> Bool in
  return value.isFunction()
}

// 2.0
@JS
func isFunction(_ value: borrowing JavaScriptValue) -> Bool {
  return value.isFunction()
}
Async functions

A Promise parameter is not supported in a @JS signature; 2.0 drops the trailing-Promise argument entirely. A Promise-returning function has three shapes in 2.0. Pick by how the underlying work produces its result.

1. Standard async method. The common case. Swift async maps to a JS Promise:

// 1.0
AsyncFunction("load") { (url: URL) -> String in
  return try loadSynchronously(url)
}

// 2.0
@JS
func load(url: URL) async throws -> String {
  return try await loadResource(url)
}

2. Checked continuation. When the result arrives through a delegate or completion handler that fires once, wrap it with withCheckedThrowingContinuation (or withCheckedContinuation for non-throwing callbacks, or an AsyncStream for repeated values). This is the usual refactor for a 1.0 AsyncFunction that took a trailing Promise instance:

// 1.0
AsyncFunction("start") { (promise: Promise) in
  scanner.start(
    onSuccess: { result in promise.resolve(result) },
    onFailure: { error in promise.reject(error) }
  )
}

// 2.0
@JS
func start() async throws -> ScanResult {
  return try await withCheckedThrowingContinuation { continuation in
    scanner.start(
      onSuccess: { result in continuation.resume(returning: result) },
      onFailure: { error in continuation.resume(throwing: error) }
    )
  }
}

Resume the continuation exactly once on every path. If the callback API cannot guarantee that, or the refactor is otherwise unsafe, keep the function on the DSL instead of forcing it.

3. Synchronous method returning a Task. The Task encodes to a promise that settles with its result. Use it when the work is naturally a Task, or when a promise is needed as a value nested inside another encoded result rather than as the function's own return:

// 2.0
@JS
func download(url: URL) -> Task<DownloadResult, any Error> {
  return Task {
    try await self.downloader.download(url)
  }
}

This shape requires the JavaScriptEncodable conformance for Task, which expo-modules-jsi provides on SDK 58 (encode-only; a JS promise does not decode back into a Task). A Task { } created here starts on the JS thread. To run the work off it, see "Returning a Task" under Threading.

Threading: the architectural difference

This is the highest-risk part of an async migration, because the code compiles and the JS signature is unchanged while the work moves onto a different thread.

The two versions schedule async work from opposite starting points:

1.0 AsyncFunction2.0 async @JS
Where the body startsoff the JS thread, from the first statementon the JS thread
When it leaves the JS threadnever runs thereat the first real suspension point
A body with no awaitstill runs off the JS threadruns entirely on the JS thread

A 2.0 async member is @JavaScriptActor-isolated and stays on the JS thread until it actually suspends. So the dangerous case is a function marked async whose body never awaits anything, or awaits only after doing substantial work. In 1.0 that body was off the JS thread from the start; migrated verbatim to 2.0, it now blocks the JS thread for its full duration. Nothing in the JS contract reveals this: the function still returns a promise.

Audit every AsyncFunction you migrate for what the body does before its first await:

  • No await at all, or synchronous work ahead of the first await: the work is on the JS thread. Treat it as a regression unless the body is trivial.

  • Blocking I/O, file or database access, image or crypto work, or an unbounded loop: never leave this on the JS actor.

  • .runOnQueue(...) in 1.0: the queue was the contract. See the continuation pattern below.

To restore the 1.0 behavior, use the @JS macro's .concurrent option:

// Body runs off the JS thread, like a 1.0 AsyncFunction.
@JS(.concurrent)
func process(input: String) async throws -> String {
  return try self.processor.process(input)
}

// The option is variadic, so it combines with an explicit JS name.
@JS("doWork", .concurrent)
func performWork() async throws {}

Only the body moves. Arguments are still decoded on the JS thread and the result is still encoded back on it, so .concurrent changes execution, not the JS contract. This makes it the preferred fix for a migrated function that relied on 1.0 background execution: the intent is explicit and the body stays as written.

Three constraints:

  • .concurrent is valid only on an async function. On anything else it is diagnosed on the @JS attribute.

  • You must still write async yourself. The macro cannot add it, but the diagnostic for a synchronous function carries a fix-it that inserts it.

  • The call sends the module or shared object off the JS thread, so in Swift 6 language mode the class must be Sendable. Module and SharedObject are not Sendable, so @unchecked Sendable is the only conformance a subclass can have. Newer expo-modules-macros versions add it themselves. Run npx --no-install expo-modules swift:expand --symbol MyModule ios/MyModule.swift: when the output has an extension MyModule: @unchecked Sendable block, do not declare it. Otherwise declare @unchecked Sendable on the class, as expo-sqlite does. Either way the compiler no longer checks this state, so check that the off-thread code touches only state that is safe to share, and say in a comment what guards it.

Returning a Task

A synchronous @JS function that returns a Task also gives JS a promise (shape 3), and the task can run the work off the JS thread. That happens only when the task does not inherit @JavaScriptActor:

// The detached task runs on the concurrent thread pool. The function returns right away.
@JS
func clearCache() -> Task<Void, any Error> {
  return Task.detached {
    try FileManager.default.removeItem(at: self.cacheDirectory)
  }
}
  • The macro isolates a synchronous @JS function to @JavaScriptActor, and Task { } inherits that isolation. The executor of that actor runs each job immediately on the current thread, so the body of a Task { } runs on the JS thread before the function even returns. Use Task.detached { }, or mark the function nonisolated so that its Task { } runs on the concurrent thread pool.

  • In Swift 6 language mode the closure sends self off the JS thread, so the class needs the @unchecked Sendable conformance described under .concurrent.

  • Throw inside the task, not from the function. An error that the function throws before it returns the task reaches JS as a synchronous exception, where a 1.0 AsyncFunction rejected its promise.

For a plain migration, prefer @JS(.concurrent): it keeps the async signature and the body as written. Return a Task when the work already is one.

Sync and async pairs

1.0 modules often register one body twice: a Function for synchronous calls and an AsyncFunction that runs the same work off the JS thread. Merge the pair with .withAsync, which binds the function under its own JS name and again under the given name as a promise-returning variant that runs on the concurrent thread pool:

// 1.0
Function("readSync") { (path: String) throws -> String in
  return try self.readFile(path)
}
AsyncFunction("read") { (path: String) throws -> String in
  return try self.readFile(path)
}

// 2.0
@JS("readSync", .withAsync("read"))
func readSync(path: String) throws -> String {
  return try readFile(path)
}

Constraints:

  • The function must be synchronous. On an async function the macro rejects the option and points to .concurrent.

  • The name must be a string literal, and the option can appear only once.

  • The variant is not isolated to the JS thread, so the body must be safe on any thread. A function isolated to a global actor such as @MainActor is rejected; mark it nonisolated when its isolation comes from elsewhere.

  • In Swift 6 language mode the class needs the @unchecked Sendable conformance described under .concurrent.

Queue-pinned functions

For .runOnQueue(.main), mark the async function @MainActor. The macro then does not isolate it to the JS thread, and the body runs on the main actor. expo-haptics migrated this way in SDK 58:

// 1.0
AsyncFunction("selectionAsync") {
  UISelectionFeedbackGenerator().selectionChanged()
}
.runOnQueue(.main)

// 2.0
@JS
@MainActor
func selectionAsync() async {
  UISelectionFeedbackGenerator().selectionChanged()
}

For a function pinned to any other queue, prefer restructuring the work onto the Swift Concurrency model (structured concurrency, an actor, or a detached task for blocking work). When that is not feasible because the queue itself is the contract, for example a library that must be called from one serial queue, convert to an async method that dispatches to that queue inside a checked continuation:

// 1.0
AsyncFunction("process") { (input: String) -> String in
  return try self.processor.process(input)
}
.runOnQueue(processingQueue)

// 2.0
@JS
func process(input: String) async throws -> String {
  return try await withCheckedThrowingContinuation { continuation in
    processingQueue.async {
      do {
        continuation.resume(returning: try self.processor.process(input))
      } catch {
        continuation.resume(throwing: error)
      }
    }
  }
}

Properties and constants

Map a getter to a getter-only @JS var; map a getter/setter pair to a settable stored or computed @JS var:

// 1.0
Property("volume") { self.volume }
  .set { self.volume = $0 }

// 2.0
@JS
var volume: Double = 1

Access control does not define JS mutability. Verify whether the declaration is syntactically settable; a stored var normally produces a JS setter.

Map a 1.0 Constant to a @JS lazy var. A 1.0 Constant runs its closure at the first read and caches the result. A lazy @JS property does the same: it is read-only from JS, and its first read stores the value as a data property on the JS object, so later reads do not call native code.

// 1.0
Constant("buildInfo") { computeBuildInfo() }

// 2.0
@JS
lazy var buildInfo = computeBuildInfo()

A @JS let also produces a read-only JS property, but it initializes with the module instance. Use it only for a cheap value whose evaluation time does not matter, such as a literal:

@JS
let apiVersion = 3

Do not map a 1.0 Property getter to a lazy var. A Property getter runs on every read, so a lazy var would freeze its first value.

Events

Replace Events(...) plus sendEvent(...) with a typed function property:

@Record
struct ProgressEvent {
  var percent: Double
}

// Explicit string preserves the old wire name.
@Event("onProgress")
var onProgress: (ProgressEvent) -> Void

func report(percent: Double) {
  onProgress(ProgressEvent(percent: percent))
}

The default @Event wire name strips a leading on and decapitalizes the remainder: Swift onProgress emits progress. 1.0 modules commonly expose onProgress. During migration, pass the original wire name explicitly unless an intentional JS breaking change was approved.

For payloads, create or reuse a JavaScriptEncodable type instead of preserving an untyped dictionary. Migrate OnStartObserving and OnStopObserving to the didStartListening(event:)/didStopListening(event:) lifecycle hooks (see Views and lifecycle).

A () -> Void event sends undefined to the listener. A 1.0 sendEvent("name") without a body sent {}, so a listener that reads a field of its argument throws after a verbatim migration. Check the JS listeners. When any of them reads the argument, keep an object payload with an empty record:

@Record
struct ReadyEvent {}

@Event("onReady")
var onReady: (ReadyEvent) -> Void

// Sends {} as before.
onReady(ReadyEvent())

Use () -> Void only when no listener reads the argument, or when the user approves the change.

Default @Event dispatch schedules onto the JS thread and is callable from other isolation contexts. Do not use sync: true: SDK 58 core has no emitSync, so a synchronous event does not build.

Shared objects

Move instance behavior from a Class(...) block onto the SharedObject subclass:

// 2.0
@SharedObject
final class Download: SharedObject {
  @JS
  init(url: URL) {
    self.url = url
  }

  @JS
  func pause() {}

  @JS
  var progress: Double { currentProgress }
}

@ExpoModule(classes: [Download.self])
final class DownloadModule: Module {}

Drop the leading owner argument used by instance DSL closures; use self in the real instance method. Preserve constructor arity and JS member names.

@SharedObject accepts any direct or indirect SharedObject subclass. That includes a SharedRef<T> subclass, such as final class AudioPlayer: SharedRef<AVPlayer>. Keep the superclass as it is.

The 1.0 DSL has no inheritance between JS classes: each Class(...) block exposes only its own entries. A @SharedObject class likewise exposes only the @JS members that it declares, so put the members of each JS class on that class.

SDK 58 core supplies the decoration and construction hooks for instance members, static members, and the @JS init. Never create both a 1.0 Class(...) entry and a 2.0 registration for the same class without confirming that core intentionally merges them.

Static members belong to shared objects, not modules: a module is exported to JS as an instance, so Swift static members on a Module class are not useful there. Keep module-level values as instance @JS members.

Static members

A static member installs on the JS class object itself, so JS reaches it as Download.supportedSchemes(), not through an instance. The 1.0 DSL has dedicated components for this: StaticFunction and StaticAsyncFunction. Unlike Function, they do not receive the instance as their first argument. There is no static property component in 1.0, so a static value was exposed as a StaticFunction returning it.

// 1.0
Class(Download.self) {
  Constructor { (url: URL) in Download(url: url) }

  // Instance function: receives the owner as its first argument.
  Function("pause") { (download: Download) in
    download.pause()
  }

  // Static: no owner argument, callable as Download.supportedSchemes()
  StaticFunction("supportedSchemes") { () -> [String] in
    Download.supportedSchemes
  }
}
// 2.0
@SharedObject
final class Download: SharedObject {
  @JS
  init(url: URL) { self.url = url }

  @JS
  func pause() {}

  @JS
  static func supportedSchemes() -> [String] {
    return Self.schemes
  }
}

StaticFunction and StaticAsyncFunction both collapse into a static (or class) Swift declaration, with async carrying the distinction, exactly as Function/AsyncFunction do for instance members. Because 1.0 had no static property component, a StaticFunction that only returns a stored value can become a @JS static var in 2.0. That changes the JS contract from a call to a property access, so do it only when the user asks; a syntax migration keeps it a function.

Instance members bind onto the class prototype, while static/class members bind onto the JS class object through a separate hook. Confirm a migrated static member by calling it on the JS class, not on an instance: an instance-side test passes whether or not static binding works.

Records

Attach @Record, remove field wrappers, and encode requiredness in the declaration:

@Record
struct Options {
  var source: URL       // required
  var retries: Int = 3  // omittable; default applies
  var label: String?    // omittable and nullable
}

Rules:

  • non-optional with no default: required

  • any property with a default: omittable

  • optional type: omittable and nullable

Preserve the 1.0 contract exactly. For example, migrate @Field var source: URL? = nil to var source: URL?, not to var source: URL, unless the user approved a breaking change.

Every non-static, non-private/fileprivate, non-lazy stored property is part of the 2.0 record surface. If the old type contains stored bookkeeping that was not a 1.0 field, make it private with a default value, move it out of the record, or leave the type on 1.0. Verify that each field supports the required JavaScriptDecodable/JavaScriptEncodable direction. Free-form fields such as [String: Any]? are accepted.

@Record applies to a struct, or to a final class with no inheritance clause. A 1.0 record class (class Options: Record) must become final and drop : Record. The macro adds the conformance, and other protocol conformances go in an extension. When the class has a superclass or subclasses, convert it to a struct only if no Swift caller relies on reference semantics; otherwise keep it on 1.0.

Unions

@Union is the typed, N-case alternative to 1.0's Either types. It applies to a non-generic enum whose every case carries exactly one associated value:

// 1.0: JS `string | SourceOptions`, unwrapped by probing each side.
@JS
func load(_ source: Either<String, SourceOptions>) throws {
  if let text: String = source.get() {
    load(url: URL(string: text))
  } else if let options: SourceOptions = source.get() {
    load(url: options.url, headers: options.headers)
  }
}
// 2.0: the same JS type, as a named enum.
@Union
enum Source {
  case text(String)
  case options(SourceOptions)   // a @Record
}

@JS
func load(_ source: Source) throws {
  switch source {               // exhaustive; each payload keeps its static type
  case .text(let text):
    load(url: URL(string: text))
  case .options(let options):
    load(url: options.url, headers: options.headers)
  }
}

The JS-visible type is unchanged: case order defines the accepted alternatives, so Either<String, SourceOptions> maps to cases in that same order. Decoding tries each case's payload in declaration order and the first match wins, which matters for overlapping types (Int/Double, URL/String): keep the 1.0 Either order, since reordering silently changes which case a given JS value lands in.

Besides switch, a value unwraps by payload type without naming the case, which is the closest analogue to 1.0's get():

let text = try source.as(String.self)              // throws on a mismatch
let options = try? source.as(SourceOptions.self)   // SourceOptions?

A type the union does not carry is a compile error, not a runtime nil. A mismatch on a held value throws, where 1.0's get() returned nil, so a migrated probe chain must become a switch or a try?.

Constraints, each a compile error: a generic enum, no cases, a case with no payload or more than one, a default value on the payload, and two cases with the identical payload spelling.

Treat adopting @Union as an API-shape change to raise with the user rather than a mechanical step: it renames nothing in JS, but it does restructure Swift call sites.

Views and lifecycle

Views are not covered by 2.0 yet. Keep UIKit View, Prop, view Events, and OnViewDidUpdateProps DSL entries on 1.0. Expansion tests alone do not prove the runtime update path exists.

The planned shape is a class marked @ExpoView whose props and event callbacks are declared once in a typed @ViewProps struct, instead of split between the native view and a hand-written JS prop type. The plugin implements both macros, but SDK 58 core does not declare them, so module source cannot use them. A module with views migrates its non-view members and keeps the view on the DSL. That is a normal mixed-mode result, not a failed migration.

Module lifecycle is core-owned rather than macro-generated. The DSL components map to hook methods with no-op defaults:

1.02.0
OnCreatedidCreate()
OnDestroywillDestroy()
OnStartObservingdidStartListening(event:)
OnStopObservingdidStopListening(event:)

Rules:

  • Use the override keyword when the class inherits Module/BaseModule; define the hooks directly (no override) when the conformance comes only from @ExpoModule. Hooks added only in a subclass of a macro module are not called; keep them on the class that declares the conformance.

  • The listening hooks receive the event name. A module-wide 1.0 OnStartObserving ignores the argument; a per-event OnStartObserving("name") becomes a comparison on it.

  • didCreate() runs after the module is registered, slightly later than 1.0 OnCreate, which fires before registration; willDestroy() runs at holder teardown. Verify nothing depends on the earlier timing before migrating OnCreate.

  • DSL lifecycle components can remain during an incremental migration and each fires exactly once, but do not implement a DSL component and its hook for the same behavior, or the work runs twice.

OnAppContextDestroys, OnAppEntersForeground, OnAppEntersBackground, and OnAppBecomesActive have no 2.0 hook. Keep them in definition().

Mixed mode

@ExpoModule may coexist with a non-empty definition(); core merges the two surfaces. Keep only unsupported entries in the DSL and avoid duplicate names across macro and DSL registrations. expo-sqlite in SDK 58 is a shipped example: its module functions, properties, event, and lifecycle hooks use the 2.0 forms, while its shared-object classes stay in definition().

Before deleting definition(), verify that it contains no:

  • Name(...) entry whose name differs from the @ExpoModule name

  • views or view events

  • lifecycle or app-context listeners

  • queue-pinned functions

Contract checklist

For every migrated member compare before and after:

ConcernMust remain stable
Moduleregistration name and requireNativeModule key
FunctionJS name, accepted arity, omitted/default behavior, sync/Promise result
PropertyJS name, read/write behavior, evaluation/caching
Eventlistener string, payload shape, timing
Recordfield names, requiredness, nullability, defaults
Shared objectconstructor shape, prototype vs constructor placement, identity
ExecutionJS actor, main actor, background queue, ordering

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Expo
Publisher
Expo (Official)
Source
expo/skills · plugins/expo-experiments/skills/expo-migrate-module · commit a9e5bd3
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Expo.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download expo-migrate-module.zip