1--- 2title: Developing and debugging a plugin 3description: Learn about development best practices and debugging techniques for Expo config plugins. 4sidebar_title: Development and debugging 5--- 6 7import { Collapsible } from '~/ui/components/Collapsible'; 8 9Developing a plugin is a great way to extend the Expo ecosystem. However, there are times you'll want to debug your plugin. This page provides some of the best practices for developing and debugging a plugin. 10 11## Develop a plugin 12 13> Use [modifier previews](https://github.com/expo/vscode-expo#expo-preview-modifier) to debug the results of your plugin live. 14 15To make plugin development easier, we've added plugin support to [`expo-module-scripts`](https://www.npmjs.com/package/expo-module-scripts). 16Refer to the [config plugins guide](https://github.com/expo/expo/tree/main/packages/expo-module-scripts#-config-plugin) for more info on using TypeScript, and Jest to build plugins. 17 18### Install dependencies 19 20Use the following dependencies in a library that provides a config plugin: 21 22```json package.json 23{ 24 "dependencies": {}, 25 "devDependencies": { 26 "expo": "^47.0.0" 27 }, 28 "peerDependencies": { 29 "expo": ">=47.0.0" 30 }, 31 "peerDependenciesMeta": { 32 "expo": { 33 "optional": true 34 } 35 } 36} 37``` 38 39- You may update the exact version of `expo` to build against a specific version. 40- For simple config plugins that depend on core, stable APIs, such as a plugin that only modifies **AndroidManifest.xml** or **Info.plist**, you can use a loose dependency such as in the example above. 41- You may also want to install [`expo-module-scripts`](https://github.com/expo/expo/blob/main/packages/expo-module-scripts/README.md) as a development dependency, but it's not required. 42 43### Import the config plugins package 44 45The `expo/config-plugins` and `expo/config` packages are re-exported from the `expo` package. 46 47{/* prettier-ignore */} 48```js 49const { /* @hide ...*//* @end */ } = require('expo/config-plugins'); 50const { /* @hide ...*//* @end */ } = require('expo/config'); 51``` 52 53Importing through the `expo` package ensures that you are using the version of the `expo/config-plugins` and `expo/config` packages that are depended on by the `expo` package. 54 55If you do not import the package through the `expo` re-export in this way, you may accidentally be importing an incompatible version 56(depending on the implementation details of module hoisting in the package manager used by the developer consuming the module) or be unable to import the module at all 57(if using "plug and play" features of a package manager such as Yarn Berry or pnpm). 58 59Config types are exported directly from `expo/config`, so there is no need to install or import from `expo/config-types`: 60 61```ts 62import { ExpoConfig, ConfigContext } from 'expo/config'; 63``` 64 65<Collapsible summary="Using SDK 46 or lower?"> 66 67For SDK 46 and lower, import the `@expo/config-plugins` package directly. This is installed automatically by the `expo` package, but not re-exported as it is in SDK 47 and higher. 68 69{/* prettier-ignore */} 70```js 71const { /* @hide ...*//* @end */ } = require('@expo/config-plugins'); 72``` 73 74</Collapsible> 75 76### Best practices for mods 77 78- Avoid regex: [static modification](#static-modification) is key. If you want to modify a value in an Android gradle file, consider using `gradle.properties`. If you want to modify some code in the Podfile, consider writing to JSON and having the Podfile read the static values. 79- Avoid performing long-running tasks like making network requests or installing Node modules in mods. 80- Do not add interactive terminal prompts in mods. 81- Generate, move, and delete new files in dangerous mods only. Failing to do so will break [introspection](#introspection). 82- Utilize built-in config plugins like `withXcodeProject` to minimize the amount of times a file is read and parsed. 83- Stick with the XML parsing libraries that prebuild uses internally, this helps prevent changes where code is rearranged needlessly. 84 85### Tooling 86 87We highly recommend installing the [Expo Tools VS Code plugin][vscode-expo] 88as this will perform automatic validation on the plugins and surface error information along with other quality of life improvements for Config Plugin development. 89 90### Setup up a playground environment 91 92You can develop plugins easily using JS, but if you want to setup Jest tests and use TypeScript, you will want a monorepo. 93 94A monorepo will enable you to work on a node module and import it in your app config like you would if it were published to npm. 95Expo config plugins have full monorepo support built-in so all you need to do is setup a project. 96 97In your monorepo's `packages/` folder, create a module, and [bootstrap a config plugin](https://github.com/expo/expo/tree/main/packages/expo-module-scripts#-config-plugin) in it. 98 99### Manually run a plugin 100 101If you aren't comfortable with setting up a monorepo, you can try manually running a plugin: 102 103- Run `npm pack` in the package with the config plugin 104- In your test project, run `npm install path/to/react-native-my-package-1.0.0.tgz`, this will add the package to your **package.json** `dependencies` object. 105- Add the package to the `plugins` array in your **app.json**: `{ "plugins": ["react-native-my-package"] }` 106 - If you have [VS Code Expo Tools][vscode-expo] installed, autocomplete should work for the plugin. 107- If you need to update the package, change the `version` in the package's **package.json** and repeat the process. 108 109### Modify AndroidManifest.xml 110 111Packages should attempt to use the built-in **AndroidManifest.xml** [merging system](https://developer.android.com/studio/build/manage-manifests) 112before using a config plugin. This can be used for static, non-optional features like permissions. 113This will ensure features are merged during build-time and not prebuild-time, which minimizes the possibility of users forgetting to prebuild. 114The drawback is that users cannot use [introspection](#introspection) to preview the changes and debug any potential issues. 115 116Here is an example of a package's **AndroidManifest.xml**, which injects a required permission: 117 118```xml AndroidManifest.xml 119<!-- @info Include <code>xmlns:android="..."</code> to use <code>android:*</code> properties like <code>android:name</code> in your manifest. --> 120<manifest package="expo.modules.filesystem" xmlns:android="http://schemas.android.com/apk/res/android"> 121 <!-- @end --> 122 <uses-permission android:name="android.permission.INTERNET"/> 123</manifest> 124``` 125 126If you're building a plugin for your local project, or if your package needs more control, then you should implement a plugin. 127 128You can use built-in types and helpers to ease the process of working with complex objects. 129Here's an example of adding a `<meta-data android:name="..." android:value="..."/>` to the default `<application android:name=".MainApplication" />`. 130 131```ts my-config-plugin.ts 132import { AndroidConfig, ConfigPlugin, withAndroidManifest } from 'expo/config-plugins'; 133import { ExpoConfig } from 'expo/config'; 134 135// Use these imports in SDK 46 and lower 136// import { AndroidConfig, ConfigPlugin, withAndroidManifest } from '@expo/config-plugins'; 137// import { ExpoConfig } from '@expo/config-types'; 138 139// Using helpers keeps error messages unified and helps cut down on XML format changes. 140const { addMetaDataItemToMainApplication, getMainApplicationOrThrow } = AndroidConfig.Manifest; 141 142export const withMyCustomConfig: ConfigPlugin = config => { 143 return withAndroidManifest(config, async config => { 144 // Modifiers can be async, but try to keep them fast. 145 config.modResults = await setCustomConfigAsync(config, config.modResults); 146 return config; 147 }); 148}; 149 150// Splitting this function out of the mod makes it easier to test. 151async function setCustomConfigAsync( 152 config: Pick<ExpoConfig, 'android'>, 153 androidManifest: AndroidConfig.Manifest.AndroidManifest 154): Promise<AndroidConfig.Manifest.AndroidManifest> { 155 const appId = 'my-app-id'; 156 // Get the <application /> tag and assert if it doesn't exist. 157 const mainApplication = getMainApplicationOrThrow(androidManifest); 158 159 addMetaDataItemToMainApplication( 160 mainApplication, 161 // value for `android:name` 162 'my-app-id-key', 163 // value for `android:value` 164 appId 165 ); 166 167 return androidManifest; 168} 169``` 170 171### Modify Info.plist 172 173Using the `withInfoPlist` is a bit safer than statically modifying the `expo.ios.infoPlist` object in the **app.json** because it reads the contents of the Info.plist and merges it with the `expo.ios.infoPlist`, this means you can attempt to keep your changes from being overwritten. 174 175Here's an example of adding a `GADApplicationIdentifier` to the **Info.plist**: 176 177```ts my-config-plugin.ts 178import { ConfigPlugin, withInfoPlist } from 'expo/config-plugins'; 179 180// Use these imports in SDK 46 and lower 181// import { ConfigPlugin, InfoPlist, withInfoPlist } from '@expo/config-plugins'; 182// import { ExpoConfig } from '@expo/config-types'; 183 184// Pass `<string>` to specify that this plugin requires a string property. 185export const withCustomConfig: ConfigPlugin<string> = (config, id) => { 186 return withInfoPlist(config, config => { 187 config.modResults.GADApplicationIdentifier = id; 188 return config; 189 }); 190}; 191``` 192 193### Modify iOS Podfile 194 195The iOS **Podfile** is the config file for CocoaPods, the dependency manager on iOS. It is similar to **package.json** for iOS. 196The **Podfile** is a ruby file (application code), which means you **cannot** safely modify it from Expo config plugins and should opt for another approach, such as [Expo Autolinking](/modules/autolinking) hooks. 197 198Currently, we do have a configuration that interacts with the CocoaPods file though. 199 200Podfile configuration is often done with environment variables: 201 202- `process.env.EXPO_USE_SOURCE` when set to `1`, Expo modules will install source code instead of xcframeworks. 203- `process.env.CI` in some projects, when set to `0`, Flipper installation will be skipped. 204 205We do expose one mechanism for safely interacting with the Podfile, but it's very limited. 206The versioned [template Podfile](https://github.com/expo/expo/tree/main/templates/expo-template-bare-minimum/ios/Podfile) is hard coded to read 207from a static JSON file **Podfile.properties.json**, we expose a mod (`ios.podfileProperties`, `withPodfileProperties`) to safely read and write from this file. 208This is used by [expo-build-properties](/versions/latest/sdk/build-properties) and to configure the JavaScript engine. 209 210### Add plugins to `pluginHistory` 211 212`_internal.pluginHistory` was created to prevent duplicate plugins from running while migrating from legacy UNVERSIONED plugins to versioned plugins. 213 214```ts my-config-plugin.ts 215import { ConfigPlugin, createRunOncePlugin } from 'expo/config-plugins'; 216 217// Use this import in SDK 46 and lower 218// import { ConfigPlugin, createRunOncePlugin } from '@expo/config-plugins'; 219 220// Keeping the name, and version in sync with it's package. 221const pkg = require('my-cool-plugin/package.json'); 222 223const withMyCoolPlugin: ConfigPlugin = config => config; 224 225// A helper method that wraps `withRunOnce` and appends items to `pluginHistory`. 226export default createRunOncePlugin( 227 // The plugin to guard. 228 withMyCoolPlugin, 229 // An identifier used to track if the plugin has already been run. 230 pkg.name, 231 // Optional version property, if omitted, defaults to UNVERSIONED. 232 pkg.version 233); 234``` 235 236### Plugin development best practices 237 238- **Instructions in your README**: If the plugin is tied to a React Native module, then you should document manual setup instructions for the package. 239 If anything goes wrong with the plugin, users should still be able to manually add the package to their project. 240 Doing this often helps you to find ways to reduce the setup, which can lead to a simpler plugin. 241 - Document the available properties for the plugin, and specify if the plugin works without props. 242 - If you can make your plugin work after running prebuild multiple times, that’s a big plus! It can improve the developer experience to be able to run `npx expo prebuild` without the `--clean` flag to sync changes. 243- **Naming conventions**: Use `withFeatureName` if cross-platform. If the plugin is platform specific, use a camel case naming with the platform right after “with”. For example, `withAndroidSplash`, `withIosSplash`. 244 There is no universally agreed upon casing for `iOS` in camel cased identifiers, we prefer this style and suggest using it for your config plugins too. 245- **Leverage built-in plugins**: Account for built-in plugins from the [prebuild config](https://github.com/expo/expo-cli/blob/master/packages/prebuild-config/src/plugins/withDefaultPlugins.ts). 246 Some features are included for historical reasons, like the ability to automatically copy and link [Google services files](https://github.com/expo/expo-cli/blob/3a0ef962a27525a0fe4b7e5567fb7b3fb18ec786/packages/config-plugins/src/ios/Google.ts#L15) defined in the app config. 247 If there is overlap, then maybe recommend the user uses the built-in types to keep your plugin as simple as possible. 248- **Split up plugins by platform**: For example — `withIosSplash`, `withAndroidSplash`. This makes using the `--platform` flag in `npx expo prebuild` a bit easier to follow in `EXPO_DEBUG` mode. 249- **Unit test your plugin**: Write Jest tests for complex modifications. If your plugin requires access to the filesystem, 250 use a mock system (we strongly recommend [`memfs`][memfs]), you can see examples of this in the [`expo-notifications`](https://github.com/expo/expo/blob/fc3fb2e81ad3a62332fa1ba6956c1df1c3186464/packages/expo-notifications/plugin/src/__tests__/withNotificationsAndroid-test.ts#L34) plugin tests. 251 - Notice the root [\*\*/\_\_mocks\_\_/\*\*/\*](https://github.com/expo/expo/tree/main/packages/expo-notifications/plugin/__mocks__) folder and [**plugin/jest.config.js**](https://github.com/expo/expo/tree/main/packages/expo-notifications/plugin/jest.config.js). 252- A TypeScript plugin is always better than a JavaScript plugin. Check out the [`expo-module-script` plugin][ems-plugin] tooling for more info. 253- Do not modify the `sdkVersion` via a config plugin, this can break commands like `expo install` and cause other unexpected issues. 254 255### Versioning 256 257By default, `npx expo prebuild` runs transformations on a [source template][source-template] associated with the Expo SDK version that a project is using. 258The SDK version is defined in the **app.json** or inferred from the installed version of `expo` that the project has. 259 260When Expo SDK upgrades to a new version of React Native for instance, the template may change significantly to account for changes in React Native or new releases of Android or iOS. 261 262If your plugin is mostly using [static modifications](#static-modification) then it will work well across versions. 263If it's using a regular expression to transform application code, then you'll definitely want to document which Expo SDK version your plugin is intended for. 264Expo releases a new version quarterly (every 3 months), and there is a [beta period](https://github.com/expo/expo/blob/main/guides/releasing/Release%20Workflow.md#stage-5---beta-release) where you can test if your plugin works with the new version before it's released. 265 266{/* TODO: versioned plugin wrapper */} 267 268### Plugin properties 269 270Properties are used to customize the way a plugin works during prebuild. 271 272Properties MUST always be static values (no functions, or promises). Consider the following types: 273 274```ts 275type StaticValue = boolean | number | string | null | StaticArray | StaticObject; 276 277type StaticArray = StaticValue[]; 278 279interface StaticObject { 280 [key: string]: StaticValue | undefined; 281} 282``` 283 284Static properties are required because the app config must be serializable to JSON for use as the app manifest. 285Static properties can also enable tooling that generates JSON schema type checking for autocomplete and IntelliSense. 286 287If possible, attempt to make your plugin work without props, this will help resolution tooling like [`expo install`](#expo-install) or [VS Code Expo Tools][vscode-expo] work better. 288Remember that every property you add increases complexity, making it harder to change in the future and increase the amount of features you'll need to test. 289Good default values are preferred over mandatory configuration when feasible. 290 291### Configure Android app startup 292 293You may find that your project requires configuration to be setup before the JS engine has started. 294For example, in `expo-splash-screen` on Android, we need to specify the resize mode in the **MainActivity.java**'s `onCreate` method. 295Instead of attempting to dangerously regex these changes into the `MainActivity` via a dangerous mod, we use a system of lifecycle hooks and static settings 296to safely ensure the feature works across all supported Android languages (Java, Kotlin), versions of Expo, and combination of config plugins. 297 298This system is made up of three components: 299 300- `ReactActivityLifecycleListeners`: An interface exposed by `expo-modules-core` to get a native callback when the project `ReactActivity`'s `onCreate` method is invoked. 301- `withStringsXml`: A mod exposed by `expo/config-plugins` which writes a property to the Android **strings.xml** file, the library can safely read the strings.xml value and do initial setup. The string XML values follow a designated format for consistency. 302- `SingletonModule` (optional): An interface exposed by `expo-modules-core` to create a shared interface between native modules and `ReactActivityLifecycleListeners`. 303 304Consider this example: We want to set a custom "value" string to a property on the Android `Activity`, directly after the `onCreate` method was invoked. 305We can do this safely by creating a node module `expo-custom`, implementing `expo-modules-core`, and Expo config plugins: 306 307First, we register the `ReactActivity` listener in our Android native module, this will only be invoked if the user has `expo-modules-core` support, setup in their project (default in projects bootstrapped with Expo CLI, Create React Native App, Ignite CLI, and Expo prebuilding). 308 309```kotlin expo-custom/android/src/main/java/expo/modules/custom/CustomPackage.kt 310package expo.modules.custom 311 312import android.content.Context 313import expo.modules.core.BasePackage 314import expo.modules.core.interfaces.ReactActivityLifecycleListener 315 316class CustomPackage : BasePackage() { 317 override fun createReactActivityLifecycleListeners(activityContext: Context): List<ReactActivityLifecycleListener> { 318 return listOf(CustomReactActivityLifecycleListener(activityContext)) 319 } 320 321 // ... 322} 323``` 324 325Next we implement the `ReactActivity` listener, this is passed the `Context` and is capable of reading from the project **strings.xml** file. 326 327```kotlin expo-custom/android/src/main/java/expo/modules/custom/CustomReactActivityLifecycleListener.kt 328package expo.modules.custom 329 330import android.app.Activity 331import android.content.Context 332import android.os.Bundle 333import android.util.Log 334import expo.modules.core.interfaces.ReactActivityLifecycleListener 335 336class CustomReactActivityLifecycleListener(activityContext: Context) : ReactActivityLifecycleListener { 337 override fun onCreate(activity: Activity, savedInstanceState: Bundle?) { 338 // Execute static tasks before the JS engine starts. 339 // These values are defined via config plugins. 340 341 var value = getValue(activity) 342 if (value != "") { 343 // Do something to the Activity that requires the static value... 344 } 345 } 346 347 // Naming is node module name (`expo-custom`) plus value name (`value`) using underscores as a delimiter 348 // i.e. `expo_custom_value` 349 // `@expo/vector-icons` + `iconName` -> `expo__vector_icons_icon_name` 350 private fun getValue(context: Context): String = context.getString(R.string.expo_custom_value).toLowerCase() 351} 352``` 353 354We must define default **string.xml** values which the user will overwrite locally by using the same `name` property in their **strings.xml** file. 355 356```xml expo-custom/android/src/main/res/values/strings.xml 357<?xml version="1.0" encoding="utf-8"?> 358<resources> 359 <string name="expo_custom_value" translatable="false"></string> 360</resources> 361``` 362 363At this point, bare users can configure this value by creating a string in their local **strings.xml** file (assuming they also have `expo-modules-core` support setup): 364 365```xml ./android/app/src/main/res/values/strings.xml 366<?xml version="1.0" encoding="utf-8"?> 367<resources> 368 <string name="expo_custom_value" translatable="false">I Love Expo</string> 369</resources> 370``` 371 372For managed users, we can expose this functionality (safely!) via an Expo config plugin: 373 374```js expo-custom/app.plugin.js 375const { AndroidConfig, withStringsXml } = require('expo/config-plugins'); 376 377function withCustom(config, value) { 378 return withStringsXml(config, config => { 379 config.modResults = setStrings(config.modResults, value); 380 return config; 381 }); 382} 383 384function setStrings(strings, value) { 385 // Helper to add string.xml JSON items or overwrite existing items with the same name. 386 return AndroidConfig.Strings.setStringItem( 387 [ 388 // XML represented as JSON 389 // <string name="expo_custom_value" translatable="false">value</string> 390 { $: { name: 'expo_custom_value', translatable: 'false' }, _: value }, 391 ], 392 strings 393 ); 394} 395``` 396 397Managed Expo users can now interact with this API like so: 398 399```json app.json 400{ 401 "expo": { 402 "plugins": [["expo-custom", "I Love Expo"]] 403 } 404} 405``` 406 407By re-running `npx expo prebuild -p` (`eas build -p android`, or `npx expo run:ios`) the user can now see the changes, safely applied in their managed project! 408 409As you can see from the example, we rely heavily on application code (expo-modules-core) to interact with application code (the native project). This ensures that our config plugins are safe and reliable, hopefully for a very long time! 410 411## Debug config plugins 412 413You can debug config plugins by running `EXPO_DEBUG=1 expo prebuild`. If `EXPO_DEBUG` is enabled, the plugin stack logs will be printed, these are useful for viewing which mods ran, and in what order they ran in. To view all static plugin resolution errors, enable `EXPO_CONFIG_PLUGIN_VERBOSE_ERRORS`, this should only be needed for plugin authors. By default, some automatic plugin errors are hidden because they're usually related to versioning issues and aren't very helpful (that is, legacy package doesn't have a config plugin yet). 414 415Running `npx expo prebuild --clean` with remove the generated native folders before compiling. 416 417You can also run `npx expo config --type prebuild` to print the results of the plugins with the mods unevaluated (no code is generated). 418 419Expo CLI commands can be profiled using `EXPO_PROFILE=1`. 420 421## Introspection 422 423Introspection is an advanced technique used to read the evaluated results of modifiers without generating any code in the project. 424This can be used to quickly debug the results of [static modifications](#static-modification) without needing to run prebuild. 425You can interact with introspection live, by using the [preview feature](https://github.com/expo/vscode-expo#expo-preview-modifier) of `vscode-expo`. 426 427You can try introspection by running `expo config --type introspect` in a project. 428 429Introspection only supports a subset of modifiers: 430 431- `android.manifest` 432- `android.gradleProperties` 433- `android.strings` 434- `android.colors` 435- `android.colorsNight` 436- `android.styles` 437- `ios.infoPlist` 438- `ios.entitlements` 439- `ios.expoPlist` 440- `ios.podfileProperties` 441 442> Introspection only works on safe modifiers (static files like JSON, XML, plist, properties), with the exception of `ios.xcodeproj` which often requires file system changes, making it non idempotent. 443 444Introspection works by creating custom base mods that work like the default base mods, except they don't write the `modResults` to disk at the end. 445Instead of persisting, they save the results to the app config under `_internal.modResults`, followed by the name of the mod 446such as the `ios.infoPlist` mod saves to `_internal.modResults.ios.infoPlist: {}`. 447 448As a real-world example, introspection is used by `eas-cli` to determine what the final iOS entitlements will be in a managed app, 449so it can sync them with the Apple Developer Portal before building. Introspection can also be used as a handy debugging and development tool. 450 451{/* TODO: Link to VS Code extension after preview feature lands */} 452 453## Legacy plugins 454 455To make `eas build` work the same as the classic `expo build` service, we added support for "legacy plugins" which are applied automatically to a project when they're installed in the project. 456 457For instance, say a project has `expo-camera` installed but doesn't have `plugins: ['expo-camera']` in their **app.json**. 458Expo CLI would automatically add `expo-camera` to the plugins to ensure that the required camera and microphone permissions are added to the project. 459The user can still customize the `expo-camera` plugin by adding it to the `plugins` array manually, and the manually defined plugins will take precedence over the automatic plugins. 460 461You can debug which plugins were added by running `expo config --type prebuild` and seeing the `_internal.pluginHistory` property. 462 463This will show an object with all plugins that were added using `withRunOnce` plugin from `expo/config-plugins`. 464 465Notice that `expo-location` uses `version: '11.0.0'`, and `react-native-maps` uses `version: 'UNVERSIONED'`. This means the following: 466 467- `expo-location` and `react-native-maps` are both installed in the project. 468- `expo-location` is using the plugin from the project's `node_modules/expo-location/app.plugin.js` 469- The version of `react-native-maps` installed in the project doesn't have a plugin, so it's falling back on the unversioned plugin that is shipped with `expo-cli` for legacy support. 470 471```json 472{ 473 _internal: { 474 pluginHistory: { 475 'expo-location': { 476 name: 'expo-location', 477 version: '11.0.0', 478 }, 479 'react-native-maps': { 480 name: 'react-native-maps', 481 version: 'UNVERSIONED', 482 }, 483 }, 484 }, 485}; 486``` 487 488For the most _stable_ experience, you should try to have no `UNVERSIONED` plugins in your project. This is because the `UNVERSIONED` plugin may not support the native code in your project. 489For instance, say you have an `UNVERSIONED` Facebook plugin in your project, if the Facebook native code or plugin has a breaking change, that will break the way your project prebuilds and cause it to error on build. 490 491## Static modification 492 493Plugins can transform application code with regular expressions, but these modifications are dangerous if the template changes over time then the regex becomes hard to predict (similarly if the user modifies a file manually or uses a custom template). Here are some examples of files you shouldn't modify manually, and alternatives. 494 495### Android Gradle Files 496 497Gradle files are written in either Groovy or Kotlin. They are used to manage dependencies, versioning, and other settings in the Android app. 498Instead of modifying them directly with the `withProjectBuildGradle`, `withAppBuildGradle`, or `withSettingsGradle` mods, utilize the static `gradle.properties` file. 499 500The `gradle.properties` is a static key/value pair that groovy files can read from. For example, say you wanted to control some toggle in Groovy: 501 502```properties gradle.properties 503# @info Safely modified using the <code>withGradleProperties()</code> mod. # 504expo.react.jsEngine=hermes 505# @end # 506``` 507 508Then later in a Gradle file: 509 510```groovy app/build.gradle 511project.ext.react = [/* @info This code would be added to the template ahead of time, but it could be regexed in using <code>withAppBuildGradle()</code> */ enableHermes: findProperty('expo.react.jsEngine') ?: 'jsc' /* @end */] 512``` 513 514- For keys in the `gradle.properties`, use camel case separated by `.`s, and usually starting with the `expo` prefix to denote that the property is managed by prebuild. 515- To access the property, use one of two global methods: 516 - `property`: Get a property, throw an error if the property is not defined. 517 - `findProperty`: Get a property without throwing an error if the property is missing. This can often be used with the `?:` operator to provide a default value. 518 519Generally, you should only interact with the Gradle file via Expo [Autolinking][autolinking], this provides a programmatic interface with the project files. 520 521### iOS AppDelegate 522 523Some modules may need to add delegate methods to the project AppDelegate, this can be done dangerously via the `withAppDelegate` mod, 524or it can be done safely by adding support for unimodules AppDelegate proxy to the native module. 525The unimodules AppDelegate proxy can swizzle function calls to native modules in a safe and reliable way. 526If the language of the project AppDelegate changes from Objective-C to Swift, the swizzler will continue to work, whereas a regex would possibly fail. 527 528Here are some examples of the AppDelegate proxy in action: 529 530- `expo-app-auth` -- [**EXAppAuthAppDelegate.m**](https://github.com/expo/expo/blob/bd7bc03ee10d89487eac25351a455bd9db155b8c/packages/expo-app-auth/ios/EXAppAuth/EXAppAuthAppDelegate.m) (openURL) 531- `expo-branch` -- [**EXBranchManager.m**](https://github.com/expo/expo/blob/636b55ab767f502f29c922a34821434efff04034/packages/expo-branch/ios/EXBranch/EXBranchManager.m) (didFinishLaunchingWithOptions, continueUserActivity, openURL) 532- `expo-notifications` -- [**EXPushTokenManager.m**](https://github.com/expo/expo/blob/bd469e421856f348d539b1b57325890147935dbc/packages/expo-notifications/ios/EXNotifications/PushToken/EXPushTokenManager.m) (didRegisterForRemoteNotificationsWithDeviceToken, didFailToRegisterForRemoteNotificationsWithError) 533- `expo-facebook` -- [**EXFacebookAppDelegate.m**](https://github.com/expo/expo/blob/e0bb254c889734f2ec6c7b688167f013587ed201/packages/expo-facebook/ios/EXFacebook/EXFacebookAppDelegate.m) (openURL) 534- `expo-file-system` -- [**EXSessionHandler.m**](https://github.com/expo/expo/blob/e0bb254c889734f2ec6c7b688167f013587ed201/packages/expo-file-system/ios/EXFileSystem/EXSessionTasks/EXSessionHandler.m) (handleEventsForBackgroundURLSession) 535 536Currently, the only known way to add support for the AppDelegate proxy to a native module, without converting that module to a unimodule, 537is to create a wrapper package: [example](https://github.com/expo/expo/pull/5165). 538 539We plan to improve this in the future. 540 541### iOS CocoaPods Podfile 542 543The `ios/Podfile` can be customized dangerously with regex, or statically via JSON: 544 545```ruby Podfile 546require 'json' 547 548# @info Import a JSON file and parse it in Ruby # 549podfileConfig = JSON.parse(File.read(File.join(__dir__, 'podfile.config.json'))) 550# @end # 551 552platform :ios, '11.0' 553 554target 'yolo27' do 555 use_unimodules! 556 config = use_native_modules! 557 use_react_native!(:path => config["reactNativePath"]) 558 559 # podfileConfig['version'] 560end 561``` 562 563Generally, you should only interact with the Podfile via Expo [Autolinking][autolinking], this provides a programmatic interface with the project files. 564 565### Custom base modifiers 566 567The Expo CLI `npx expo prebuild` command uses [`@expo/prebuild-config`][prebuild-config] to get the default base modifiers. These defaults only manage a subset of common files, if you want to manage custom files you can do that locally by adding new base modifiers. 568 569For example, say you wanted to add support for managing the `ios/*/AppDelegate.h` file, you could do this by adding a `ios.appDelegateHeader` modifier. 570 571> This example uses `ts-node` for simple local TypeScript support, this isn't strictly necessary. [Learn more](/guides/typescript/#appconfigjs). 572 573```ts withAppDelegateHeaderBaseMod.ts 574import { ConfigPlugin, IOSConfig, Mod, withMod, BaseMods } from 'expo/config-plugins'; 575import fs from 'fs'; 576 577/** 578 * A plugin which adds new base modifiers to the prebuild config. 579 */ 580export function withAppDelegateHeaderBaseMod(config) { 581 return BaseMods.withGeneratedBaseMods<'appDelegateHeader'>(config, { 582 platform: 'ios', 583 providers: { 584 // Append a custom rule to supply AppDelegate header data to mods on `mods.ios.appDelegateHeader` 585 appDelegateHeader: BaseMods.provider<IOSConfig.Paths.AppDelegateProjectFile>({ 586 // Get the local filepath that should be passed to the `read` method. 587 getFilePath({ modRequest: { projectRoot } }) { 588 const filePath = IOSConfig.Paths.getAppDelegateFilePath(projectRoot); 589 // Replace the .m with a .h 590 if (filePath.endsWith('.m')) { 591 return filePath.substr(0, filePath.lastIndexOf('.')) + '.h'; 592 } 593 // Possibly a Swift project... 594 throw new Error(`Could not locate a valid AppDelegate.h at root: "${projectRoot}"`); 595 }, 596 // Read the input file from the filesystem. 597 async read(filePath) { 598 return IOSConfig.Paths.getFileInfo(filePath); 599 }, 600 // Write the resulting output to the filesystem. 601 async write(filePath: string, { modResults: { contents } }) { 602 await fs.promises.writeFile(filePath, contents); 603 }, 604 }), 605 }, 606 }); 607} 608 609/** 610 * (Utility) Provides the AppDelegate header file for modification. 611 */ 612export const withAppDelegateHeader: ConfigPlugin<Mod<IOSConfig.Paths.AppDelegateProjectFile>> = ( 613 config, 614 action 615) => { 616 return withMod(config, { 617 platform: 'ios', 618 mod: 'appDelegateHeader', 619 action, 620 }); 621}; 622 623// (Example) Log the contents of the modifier. 624export const withSimpleAppDelegateHeaderMod = config => { 625 return withAppDelegateHeader(config, config => { 626 console.log('modify header:', config.modResults); 627 return config; 628 }); 629}; 630``` 631 632To use this new base mod, add it to the plugins array. The base mod **MUST** be added last after all other plugins that use the mod, this is because it must write the results to disk at the end of the process. 633 634```js app.config.js 635// Required for external files using TS 636require('ts-node/register'); 637 638import { 639 withAppDelegateHeaderBaseMod, 640 withSimpleAppDelegateHeaderMod, 641} from './withAppDelegateHeaderBaseMod.ts'; 642 643export default ({ config }) => { 644 if (!config.plugins) config.plugins = []; 645 config.plugins.push( 646 withSimpleAppDelegateHeaderMod, 647 648 // Base mods MUST be last 649 withAppDelegateHeaderBaseMod 650 ); 651 return config; 652}; 653``` 654 655For more info, see [the PR that adds support](https://github.com/expo/expo-cli/pull/3852) for this feature. 656 657## expo install 658 659Node modules with config plugins can be added to the project's app config automatically by using the `expo install` command. [Related PR](https://github.com/expo/expo-cli/pull/3437). 660 661This makes setup a bit easier and helps prevent users from forgetting to add a plugin. 662 663This does come with a couple of caveats: 664 6651. Packages must export a plugin via **app.plugin.js**, this rule was added to prevent popular packages like `lodash` from being mistaken for a config plugin and breaking the prebuild. 6662. There is currently no mechanism for detecting if a config plugin has mandatory props. Because of this, `expo install` will only add the plugin, and not attempt to add any extra props. For example, `expo-camera` has optional extra props, so `plugins: ['expo-camera']` is valid, but if it had mandatory props then `expo-camera` would throw an error. 6673. Plugins can only be automatically added when the user's project uses a static app config (**app.json** and **app.config.json**). 668 If the user runs `expo install expo-camera` in a project with an **app.config.js**, they'll see a warning like: 669 670``` 671Cannot automatically write to dynamic config at: app.config.js 672Please add the following to your app config 673 674{ 675 "plugins": [ 676 "expo-camera" 677 ] 678} 679``` 680 681[config-docs]: /versions/latest/config/app/ 682[prebuild-config]: https://github.com/expo/expo-cli/tree/main/packages/prebuild-config#readme 683[cli-prebuild]: /more/expo-cli//#expo-prebuild 684[configplugin]: https://github.com/expo/expo-cli/blob/3a0ef962a27525a0fe4b7e5567fb7b3fb18ec786/packages/config-plugins/src/Plugin.types.ts#L76 685[source-template]: https://github.com/expo/expo/tree/main/templates/expo-template-bare-minimum 686[expo-beta-docs]: https://github.com/expo/expo/tree/main/guides/releasing/Release%20Workflow.mdx#stage-5---beta-release 687[vscode-expo]: https://marketplace.visualstudio.com/items?itemName=expo.vscode-expo-tools 688[ems-plugin]: https://github.com/expo/expo/tree/main/packages/expo-module-scripts#-config-plugin 689[xml2js]: https://www.npmjs.com/package/xml2js 690[expo-plist]: https://www.npmjs.com/package/@expo/plist 691[memfs]: https://www.npmjs.com/package/memfs 692[emc]: https://github.com/expo/expo/tree/main/packages/expo-modules-core 693[autolinking]: /more/glossary-of-terms#autolinking 694