This is now documented in the SwiftDocCPlugin
guide:
Transforming for Static Hosting
Alternatively, if you’d like to avoid setting custom routing rules on
your server or are hosting in an environment where this isn’t
possible, you can generate documentation that has been transformed for
static hosting.
Example
Warning
You'll see a few Unfortunately
's in this answer. I highly recommend you avoid using DocC for the reasons explained below. If you find workarounds to these, do let me know :). In terms of comparison, DocC competes with so many successful static site generators and open source documentation frameworks (Docusaurus) and doesn't do very well.
Steps
- Add SwiftDocCPlugin to your
Package.swift
:
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
# Update to your target, from `Package.swift`
TARGET_NAME=SlothCreator
OUTPUT_DIR=docs
swift package --allow-writing-to-directory $OUTPUT_DIR \
generate-documentation \
--target $TARGET_NAME \
--disable-indexing \
--output-path $OUTPUT_DIR \
--transform-for-static-hosting
cd docs
- Run it locally:
- You can start a server to serve your files: run
python3 -m http.server
.
- Open the website in a browser:
http://localhost:8000/documentation/target_name/
- Warning: It still needs a webserver and the website doesn't work very well. If you visit
http://localhost:8000
, you get an error: The page you’re looking for can’t be found.
You cannot just open the index.html
page without a server.
- Deploy it using GitHub pages, or Cloudflare Workers Sites:
- When you deploy, this is taken care of, since GitHub pages, Cloudflare Workers Sites serve these pages. Unfortunately, this won't work with Cloudflare Pages, since it can't build Swift documentation.
- Unfortunately, the paths is not configurable:
/<output-path-specified-by-command-line>/documentation/<target-name>
, for example, it could be: localhost:8000/documentation/slothcreator/
- Unfortunately, you have to commit your generated documentation files into git. The Apple docs had shown the command:
git add docs
and git commit -m "Update GitHub pages documentation site."
. This is because services like Github Pages, Cloudflare Workers Sites can't build your site for you.
- Unfortunately, this generated folder (
docs/
) is 31MB and contains what appears to be unnecessary files and large, unoptimised assets. For some services eg Cloudflare Workers Sites, you have to upload the entire website every time you publish.
- Unfortunately, you need to regenerate and commit all the files separately if you want to put them at different paths, since you need to use a different command. See comments in build.sh. This means it's not 31MB, but N x 31MB, where N is the number of sites you have.