我正在将一个项目从Cocoapods迁移到SPM,但是在一个问题上,我们只需要在条件情况下使用某些依赖项。
Cocoapods有一个简单的解决方案:
if ENV['enabled'].to_i == 1
pod 'Google'
end 据我所知,SPM中只部分支持条件依赖,这对我的问题还不够:https://github.com/apple/swift-evolution/blob/main/proposals/0273-swiftpm-conditional-target-dependencies.md
我正在考虑创建一个构建阶段脚本,根据环境变量条件手动将框架作为目标成员。
寻找一个可行的解决方案。
发布于 2022-10-11 13:35:56
"Package.swift“是一个常规的快速文件,您可以为您的逻辑和内部条件编写任何代码。例如,您可以使用ProcessInfo检查环境变量,并组装所需的依赖数组:
import PackageDescription
import Foundation
let useRealm = ProcessInfo.processInfo.environment["realm"] == "1"
let packageDependencies: [Package.Dependency] = useRealm
? [.package(url: "https://github.com/realm/realm-cocoa.git", from: "10.15.1")]
: []
let targetDependencies: [Target.Dependency] = useRealm
? [.product(name: "Realm", package: "realm-cocoa")]
: []
let package = Package(
name: "MyPackage",
platforms: [
.iOS(.v12),
.macOS(.v10_14)
],
products: [
.library(name: "MyPackage", targets: ["MyPackage"]),
],
dependencies: packageDependencies,
targets: [
.target(name: "MyPackage", dependencies: targetDependencies),
.testTarget(name: "MyPackageTests", dependencies: ["MyPackage"]),
]
)现在您可以在没有依赖项的情况下构建包:
$ xcrun --sdk macosx swift build
Building for debugging...
[2/2] Emitting module MyPackage
Build complete! (0.77s)并通过在环境变量中设置realm=1来处理领域依赖关系:
$ export realm=1
$ xcrun --sdk macosx swift build
Fetching https://github.com/realm/realm-cocoa.git from cache
Fetched https://github.com/realm/realm-cocoa.git (2.12s)
Computing version for https://github.com/realm/realm-cocoa.git
Computed https://github.com/realm/realm-cocoa.git at 10.32.0 (0.02s)
Fetching https://github.com/realm/realm-core from cache
Fetched https://github.com/realm/realm-core (1.37s)
Computing version for https://github.com/realm/realm-core
Computed https://github.com/realm/realm-core at 12.9.0 (0.02s)
Creating working copy for https://github.com/realm/realm-cocoa.git
Working copy of https://github.com/realm/realm-cocoa.git resolved at 10.32.0
Creating working copy for https://github.com/realm/realm-core
Working copy of https://github.com/realm/realm-core resolved at 12.9.0
Building for debugging...
[63/63] Compiling MyPackage MyPackage.swift
Build complete! (41.64s)https://stackoverflow.com/questions/73987302
复制相似问题