How to publish a crate with optional dependency?

Viewed 172

I have some trouble about publishing crates with optional dependencies.

First, I execute cargo publish, but I don't see any optional dependencies compiled.

Then, I run cargo publish --all-features. The dependencies were compiled, but I don't see any modules with optional dependency in the documentation generated by crates.io.

What is the correct way to publish a crate with an optional dependency, which does not a default feature setting in Cargo.toml?

1 Answers

cargo publish is the correct way to do it.

If you want that docs.rs (not crates.io) builds your documentation with some features enabled, use the package.metadata.docs.rs section in your Cargo.toml. I use the Cargo.toml from the petgraph crate as an example (stripped):

[package]
name = "petgraph"
version = "0.6.0"
description = "Graph data structure library. Provides graph types and graph algorithms."
edition = "2018"

[dependencies]
fixedbitset = { version = "0.4.0", default-features = false }
indexmap = { version = "1.6.2" }
quickcheck = { optional = true, version = "0.8", default-features = false }
serde = { version = "1.0", optional = true }
serde_derive = { version = "1.0", optional = true }

[...]

[features]
default = ["graphmap", "stable_graph", "matrix_graph"]
graphmap = []
stable_graph = []
matrix_graph = []
serde-1 = ["serde", "serde_derive"]

[package.metadata.docs.rs]
features = ["serde-1", "quickcheck"]
Related