Using the Swift Package Manager command plugin for Swift-DocC

Using the Swift Package Manager command plugin for Swift-DocC

This reference shows how to use the Swift Package Manager command plugin for Swift-DocC to export documentation for static web hosting.

Alongside the release of Swift 5.6 there is now a Swift-DocC Plugin that can be used with Swift Package Manager. It can support you to create Swift-DocC documentation for Swift Package libraries and executables. Apple also provides some more extensive information on its usage in the official Apple Developer Documentation.

Let's have a look at how this works.

To use the Swift-DocC plugin with your package, Swift 5.6 is required and you need to add it as a dependency to your project:

let package = Package(
    // name, platforms, products, etc.
    dependencies: [
        // other dependencies
        .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
    ],
    targets: [
        // targets
    ]
)

After adding the dependency, you can build documentation for libraries and executables in that package as well as their dependencies by running the following from the command-line:

$ swift package generate-documentation

Using this command, you will automatically generate the documentation for all targets defined in your project and their dependencies. You can of course also generate documentation for only specific targets and export this to specific directories, using the --output-path and --target MyFramework flags.

As already introduced in "Publishing DocC Documentation as a Static Website on GitHub Pages", the DocC archive can also be converted for static website hosting. This is now even more convenient. For example, you could run the following commnad:

swift package --allow-writing-to-directory ./docs \
    generate-documentation --target MyFramework --output-path ./docs \
    --transform-for-static-hosting --hosting-base-path MyFramework

This would result in the documentation for the target MyFramework being exported to the /docs folder. It is then transformed for static hosting with the --transform-for-static-hosting flag and uses the base URL path of MyFramework with the --hosting-base-path flag. In the context of GitHub pages, this base path would be the name of the repository. For hosting on any other web server it might be the base URL of that website, like example.com.

To get started with the new plugin, Apple provides some nice articles inside the plugin documentation as well:

At this stage, DocC seems very well documented and quite capable to supercharge your documentation. We look forward to seeing what the community will create with it.