在本地 SPM 包中导入本地 SPM 库

Import local SPM Library in local SPM package

我有一个包含 2 个库的本地 SPM 包,我想将其中一个库导入到另一个本地 SPM 包中: 包含库的文件:

let package = Package(
    name: "LocationService",
    platforms: [.iOS(.v13)],
    products: [
        .library(
            name: "LocationService",
            type: .dynamic,
            targets: ["LocationService"]),
        .library(
          name: "LocationLiveClient",
          type: .dynamic,
          targets: ["LocationLiveClient"]),
    ],
    targets: [
        .target(
            name: "LocationService",
            dependencies: []),
        .target(
            name: "LocationLiveClient",
            dependencies: ["LocationService"],
            path: "Sources/LocationLiveClient"),
    ]
)

导入库的文件:

let package = Package(
    name: "HomePage",
    products: [
        .library(
            name: "HomePage",
            type: .dynamic,
            targets: ["HomePage"])
    ],
    dependencies: [
      .package(path: "../RouterService"),
      .package(path: "../LocationService/Sources/LocationLiveClient"),
    ],
    targets: [
        .target(
            name: "HomePage",
            dependencies: ["RouterService", "LocationLiveClient"])
    ]
)

这里有几个问题需要解决。

(如果您的设计要求是使用'dynamic' linking,那么这种方法可能不适合您。)

  • type: .dynamic:

除非你绝对需要保证库linking是如何实现的,否则建议你将此保留为默认值nil(只需删除该行)。这允许 swift 包管理器确定如何最好地 link 库(默认为 'static')。

  • .package(path: "../LocationService/Sources/LocationLiveClient"),

LocationLiveClientLocationService 包的产品和目标。在这里的依赖项中,应该引用整个包。所以将其更改为 .package(path: "../LocationService"),

  • dependencies: ["RouterService", "LocationLiveClient"])

一旦更改为依赖于整个位置服务包,编译器就需要一些额外的信息。您可以更新目标依赖项以专门使用 LocationService 包中的 LocationLiveClient 库:.product(name: "LocationLiveClient", package: "LocationService").

完成这些更改后,您最终会得到如下的包定义:

let package = Package(
    name: "HomePage",
    products: [
        .library(
            name: "HomePage",
            targets: ["HomePage"]),
    ],
    dependencies: [
        .package(path: "../RouterService"),
        .package(path: "../LocationService"),
    ],
    targets: [
        .target(
            name: "HomePage",
            dependencies: [
                "RouterService",
                .product(name: "LocationLiveClient", package: "LocationService")
            ]
        ),
    ]
)

然后您应该能够 import LocationLiveClient 如预期的那样。


旁注:假设您的 'LocationService' 包具有以下文件夹结构,那么您可以安全地从 LocationLiveClient 目标定义中删除 path: "Sources/LocationLiveClient"

LocationService
-> Sources
  -> LocationService
  -> LocationLiveClient