Skip to content

Instantly share code, notes, and snippets.

@ridvanaltun
Last active October 26, 2024 21:10
Show Gist options
  • Save ridvanaltun/a02a9a8a8d4bbd354a5cd875a20cf21f to your computer and use it in GitHub Desktop.
Save ridvanaltun/a02a9a8a8d4bbd354a5cd875a20cf21f to your computer and use it in GitHub Desktop.
Auto-linking configuration for React-Native 0.75.4 IOS App Clip

I did same thing for iOS like I do before for Android: https://gist.github.com/ridvanaltun/5bf4e072e8db7a4ecd93770c542b1387

  1. Mark don't needed libraries with appClip key in react-native.config.js file:
module.exports = {
  dependencies: {
    ['react-native-camera']: {
      appClip: false,
    },
  },
};
  1. Update Podfile:
# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
  'require.resolve(
    "react-native/scripts/react_native_pods.rb",
    {paths: [process.argv[1]]},
  )', __dir__]).strip

platform :ios, min_ios_version_supported
prepare_react_native_project!

linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
  Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
  use_frameworks! :linkage => linkage.to_sym
end

target 'Example' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'ExampleTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
    react_native_post_install(
      installer,
      config[:reactNativePath],
      :mac_catalyst_enabled => false,
      # :ccache_enabled => true
    )
  end
end

+target 'ExampleAppClip' do
+  ENV['APP_CLIP'] = "true"
+
+  config = use_native_modules!
+
+  use_react_native!(
+    :path => config[:reactNativePath],
+    # An absolute path to your application root.
+    :app_path => "#{Pod::Config.instance.installation_root}/.."
+  )
+end
  1. Update @react-native-community/cli-config:

node_modules/@react-native-community/cli-config/build/schema.js

Go to file: https://gist.github.com/ridvanaltun/a02a9a8a8d4bbd354a5cd875a20cf21f#file-schema-diff

  1. Update autolinking.rb in react-native:

node_modules/react-native/scripts/cocoapods/autolinking.rb

Go to file: https://gist.github.com/ridvanaltun/a02a9a8a8d4bbd354a5cd875a20cf21f#file-autolinking-diff

  1. Patch all changes
npx patch-package @react-native-community/cli-config
npx patch-package react-native
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
require 'json'
require 'pathname'
require 'cocoapods'
require_relative './autolinking_utils.rb'
require_relative '../react_native_pods.rb'
# Your project will have to depend on the @react-native-community/cli if you use this method
# for listing React native modules.
#
# Parameters:
# - config_command: the command to run to get the application's current config, e.g. ['npx', '@react-native-community/cli', 'config']
def list_native_modules!(config_command)
if !(config_command.is_a? Array and config_command.size > 0)
Pod::UI.warn "Expected a list_native_modules! to be called with a config command", [
"Unable to autolink if no config is provided for the current project."
]
exit(1)
end
# Ignore stderr output, we're only interested in stdout and the return code. Libraries can output warnings to
# stderr which create problems for JSON deserializing.
json, _, status = Pod::Executable.capture_command(config_command[0], config_command[1..], capture: :both)
if not status.success?
Pod::UI.warn "The command: '#{config_command.join(" ").bold.yellow}' returned a status code of #{status.exitstatus.to_s.bold.red}", [
"In order to autolink using Cocoapods, this framework uses @react-native-community/cli to discover React Native native modules",
"Please either add it: yarn add -D @react-native-community/cli or consult your framework's documentation."
]
exit(status.exitstatus)
end
config = JSON.parse(json)
packages = config["dependencies"]
ios_project_root = Pathname.new(config["project"]["ios"]["sourceDir"])
react_native_path = Pathname.new(config["reactNativePath"])
found_pods = []
+ app_clip_target = ENV['APP_CLIP'] == 'true'
packages.each do |package_name, package|
next unless package_config = package["platforms"]["ios"]
name = package["name"]
podspec_path = package_config["podspecPath"]
script_phases = package_config["scriptPhases"]
configurations = package_config["configurations"]
+ app_clip_supported = package["appClip"] != false
+
+ next unless (app_clip_target && app_clip_supported) || !app_clip_target
# Add a warning to the queue and continue to the next dependency if the podspec_path is nil/empty
if podspec_path.nil? || podspec_path.empty?
Pod::UI.warn("list_native_modules! skipped the react-native dependency '#{name}'. No podspec file was found.",
[
"Check to see if there is an updated version that contains the necessary podspec file",
"Contact the library maintainers or send them a PR to add a podspec. The react-native-webview podspec is a good example of a package.json driven podspec. See https://github.com/react-native-community/react-native-webview/blob/master/react-native-webview.podspec",
"If necessary, you can disable autolinking for the dependency and link it manually. See https://github.com/react-native-community/cli/blob/main/docs/autolinking.md#how-can-i-disable-autolinking-for-unsupported-library"
])
next
end
spec = Pod::Specification.from_file(podspec_path)
# Skip pods that do not support the platform of the current target.
next unless AutolinkingUtils.is_platform_supported?(current_target_definition, spec)
podspec_dir_path = Pathname.new(File.dirname(podspec_path))
relative_path = podspec_dir_path.relative_path_from ios_project_root
found_pods.push({
"configurations": configurations,
"name": name,
"root": package["root"],
"path": relative_path.to_path,
"podspec_path": podspec_path,
"script_phases": script_phases
})
end
if found_pods.size > 0
pods = found_pods.map { |p| p[:name] }.sort.to_sentence
Pod::UI.puts "Found #{found_pods.size} #{"module".pluralize(found_pods.size)} for target `#{current_target_definition.name}`"
end
return {
"ios_packages": found_pods,
"ios_project_root_path": ios_project_root.to_s,
"react_native_path": react_native_path.relative_path_from(ios_project_root).to_s
}
end
# Your project will have to depend on the @react-native-community/cli if you use this method
# for listing React native modules.
#
# Parameters:
# - config:
# - :ios_packages - Array of React Native iOS packages, e.g. [{ package_name: "Foo", package: { .. }}, ...]
# - :ios_project_root_path - Absolute path to the react_native project's ios folder, e.g. /Users/foobar/project/rn_project/ios
# - :react_native_path - Relative path to the react_native from the project, e.g. ./node_modules/react-native
def link_native_modules!(config)
Pod::UI.puts "link_native_modules! #{config}"
if !(
config[:ios_packages].is_a? Array and
config[:ios_project_root_path].is_a? String and
config[:react_native_path].is_a? String
)
Pod::UI.warn("link_native_modules! has been called with a malformed 'config' parameter",
[
"This is the config argument passed: #{config.inspect}",
]);
exit(1)
end
ios_project_root = config[:ios_project_root_path]
packages = config[:ios_packages]
found_pods = []
packages.each do |package|
podspec_path = package[:podspec_path]
configurations = package[:configurations]
# Add a warning to the queue and continue to the next dependency if the podspec_path is nil/empty
if podspec_path.nil? || podspec_path.empty?
Pod::UI.warn("use_native_modules! skipped the react-native dependency '#{package[:name]}'. No podspec file was found.",
[
"Check to see if there is an updated version that contains the necessary podspec file",
"Contact the library maintainers or send them a PR to add a podspec. The react-native-webview podspec is a good example of a package.json driven podspec. See https://github.com/react-native-community/react-native-webview/blob/master/react-native-webview.podspec",
"If necessary, you can disable autolinking for the dependency and link it manually. See https://github.com/react-native-community/cli/blob/main/docs/autolinking.md#how-can-i-disable-autolinking-for-unsupported-library"
])
next
end
spec = Pod::Specification.from_file(podspec_path)
# Don't try track packages that exclude our platforms
next unless AutolinkingUtils.is_platform_supported?(current_target_definition, spec)
# We want to do a look up inside the current CocoaPods target
# to see if it's already included, this:
# 1. Gives you the chance to define it beforehand
# 2. Ensures CocoaPods won't explode if it's included twice
#
this_target = current_target_definition
existing_deps = current_target_definition.dependencies
# Skip dependencies that the user already activated themselves.
next if existing_deps.find do |existing_dep|
existing_dep.name.split('/').first == spec.name
end
podspec_dir_path = Pathname.new(File.dirname(podspec_path))
relative_path = podspec_dir_path.relative_path_from ios_project_root
# Register the found React Native module into our collection of Pods.
pod spec.name, :path => relative_path.to_path, :configurations => configurations
if package[:script_phases] && !this_target.abstract?
# Can be either an object, or an array of objects
Array(package[:script_phases]).each do |phase|
# see https://www.rubydoc.info/gems/cocoapods-core/Pod/Podfile/DSL#script_phase-instance_method
# for the full object keys
Pod::UI.puts "Adding a custom script phase for Pod #{spec.name}: #{phase["name"] || 'No name specified.'}"
# Support passing in a path relative to the root of the package
if phase["path"]
phase["script"] = File.read(File.expand_path(phase["path"], package[:root]))
phase.delete("path")
end
# Support converting the execution position into a symbol
phase["execution_position"] = phase["execution_position"]&.to_sym
phase = Hash[phase.map { |k, v| [k.to_sym, v] }]
script_phase phase
end
end
found_pods.push spec
end
if found_pods.size > 0
pods = found_pods.map { |p| p.name }.sort.to_sentence
Pod::UI.puts "Auto-linking React Native #{"module".pluralize(found_pods.size)} for target `#{current_target_definition.name}`: #{pods}"
end
return {
:reactNativePath => config[:react_native_path]
}
end
$default_command = ['node', '-e', "process.argv=['', '', 'config'];require('@react-native-community/cli').run()"];
# Autolink your native modules
#
# Parameters:
# - config_command: the command to run to get the application's current config, e.g. ['npx', '@react-native-community/cli', 'config'],
# you can override this if you'd like to avoid the dependency. e.g. ['cat', 'your_config.json']
def use_native_modules!(config_command = $default_command)
return link_native_modules!(list_native_modules!(config_command))
end
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.projectConfig = exports.dependencyConfig = void 0;
function _joi() {
const data = _interopRequireDefault(require('joi'));
_joi = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* This schema is used by `cli-config` to validate the structure. Make sure
* this file stays up to date with `cli-types` package.
*
* In the future, it would be great to generate this file automatically from the
* Typescript types.
*/
const map = (key, value) =>
_joi().default.object().unknown(true).pattern(key, value);
/**
* Schema for CommandT
*/
const command = _joi().default.object({
name: _joi().default.string().required(),
description: _joi().default.string(),
usage: _joi().default.string(),
func: _joi().default.func().required(),
options: _joi()
.default.array()
.items(
_joi()
.default.object({
name: _joi().default.string().required(),
description: _joi().default.string(),
parse: _joi().default.func(),
default: _joi()
.default.alternatives()
.try(
_joi().default.bool(),
_joi().default.number(),
_joi().default.string().allow(''),
_joi().default.func(),
),
})
.rename('command', 'name', {
ignoreUndefined: true,
}),
),
examples: _joi()
.default.array()
.items(
_joi().default.object({
desc: _joi().default.string().required(),
cmd: _joi().default.string().required(),
}),
),
});
/**
* Schema for HealthChecksT
*/
const healthCheck = _joi().default.object({
label: _joi().default.string().required(),
healthchecks: _joi()
.default.array()
.items(
_joi().default.object({
label: _joi().default.string().required(),
isRequired: _joi().default.bool(),
description: _joi().default.string(),
getDiagnostics: _joi().default.func(),
win32AutomaticFix: _joi().default.func(),
darwinAutomaticFix: _joi().default.func(),
linuxAutomaticFix: _joi().default.func(),
runAutomaticFix: _joi().default.func().required(),
}),
),
});
/**
* Schema for UserDependencyConfig
*/
const dependencyConfig = _joi()
.default.object({
dependency: _joi()
.default.object({
platforms: map(_joi().default.string(), _joi().default.any())
.keys({
ios: _joi()
.default // IOSDependencyParams
.object({
scriptPhases: _joi()
.default.array()
.items(_joi().default.object()),
configurations: _joi()
.default.array()
.items(_joi().default.string())
.default([]),
})
.allow(null),
android: _joi()
.default // AndroidDependencyParams
.object({
sourceDir: _joi().default.string(),
manifestPath: _joi().default.string(),
packageName: _joi().default.string(),
packageImportPath: _joi().default.string(),
packageInstance: _joi().default.string(),
dependencyConfiguration: _joi().default.string(),
buildTypes: _joi()
.default.array()
.items(_joi().default.string())
.default([]),
libraryName: _joi().default.string().allow(null),
componentDescriptors: _joi()
.default.array()
.items(_joi().default.string())
.allow(null),
cmakeListsPath: _joi().default.string().allow(null),
cxxModuleCMakeListsModuleName: _joi()
.default.string()
.allow(null),
cxxModuleCMakeListsPath: _joi().default.string().allow(null),
cxxModuleHeaderName: _joi().default.string().allow(null),
})
.allow(null),
})
.default(),
})
.default(),
platforms: map(
_joi().default.string(),
_joi().default.object({
npmPackageName: _joi().default.string().optional(),
dependencyConfig: _joi().default.func(),
projectConfig: _joi().default.func(),
linkConfig: _joi().default.func(),
}),
).default({}),
commands: _joi().default.array().items(command).default([]),
healthChecks: _joi().default.array().items(healthCheck).default([]),
})
.unknown(true)
.default();
/**
* Schema for ProjectConfig
*/
exports.dependencyConfig = dependencyConfig;
const projectConfig = _joi()
.default.object({
dependencies: map(
_joi().default.string(),
_joi()
.default.object({
root: _joi().default.string(),
+ appClip: _joi().default.bool(),
platforms: map(_joi().default.string(), _joi().default.any()).keys({
ios: _joi()
.default // IOSDependencyConfig
.object({
podspecPath: _joi().default.string(),
version: _joi().default.string(),
configurations: _joi()
.default.array()
.items(_joi().default.string())
.default([]),
scriptPhases: _joi()
.default.array()
.items(_joi().default.object())
.default([]),
})
.allow(null),
android: _joi()
.default // AndroidDependencyConfig
.object({
sourceDir: _joi().default.string(),
packageImportPath: _joi().default.string(),
packageInstance: _joi().default.string(),
dependencyConfiguration: _joi().default.string(),
buildTypes: _joi()
.default.array()
.items(_joi().default.string())
.default([]),
libraryName: _joi().default.string().allow(null),
componentDescriptors: _joi()
.default.array()
.items(_joi().default.string())
.allow(null),
cmakeListsPath: _joi().default.string().allow(null),
})
.allow(null),
}),
})
.allow(null),
).default({}),
reactNativePath: _joi().default.string(),
project: map(_joi().default.string(), _joi().default.any())
.keys({
ios: _joi()
.default // IOSProjectParams
.object({
sourceDir: _joi().default.string(),
watchModeCommandParams: _joi()
.default.array()
.items(_joi().default.string()),
// @todo remove for RN 0.75
unstable_reactLegacyComponentNames: _joi()
.default.array()
.items(_joi().default.string())
.optional(),
automaticPodsInstallation: _joi().default.bool().default(false),
assets: _joi()
.default.array()
.items(_joi().default.string())
.default([]),
})
.default({}),
android: _joi()
.default // AndroidProjectParams
.object({
sourceDir: _joi().default.string(),
appName: _joi().default.string(),
manifestPath: _joi().default.string(),
packageName: _joi().default.string(),
dependencyConfiguration: _joi().default.string(),
watchModeCommandParams: _joi()
.default.array()
.items(_joi().default.string()),
// @todo remove for RN 0.75
unstable_reactLegacyComponentNames: _joi()
.default.array()
.items(_joi().default.string())
.optional(),
assets: _joi()
.default.array()
.items(_joi().default.string())
.default([]),
})
.default({}),
})
.default(),
assets: _joi().default.array().items(_joi().default.string()).default([]),
commands: _joi().default.array().items(command).default([]),
platforms: map(
_joi().default.string(),
_joi().default.object({
npmPackageName: _joi().default.string().optional(),
dependencyConfig: _joi().default.func(),
projectConfig: _joi().default.func(),
linkConfig: _joi().default.func(),
}),
).default({}),
})
.unknown(true)
.default();
exports.projectConfig = projectConfig;
//# sourceMappingURL=/Users/thymikee/Developer/oss/rncli/packages/cli-config/build/schema.js.map
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment