Can Cargo download and build dependencies without also building the application?

There is no native support for building just the dependencies in Cargo, as far as I know. There is an open issue for it. I wouldn’t be surprised if you could submit something to Cargo to accomplish it though, or perhaps create a third-party Cargo addon. I’ve wanted this functionality for cargo doc as well, when my own code is too broken to compile 😉

However, the Rust playground that I maintain does accomplish your end goal. There’s a base Docker container that installs Rustup and copies in a Cargo.toml with all of the crates available for the playground. The build steps create a blank project (with a dummy src/lib.rs), then calls cargo build and cargo build --release to compile the crates:

RUN cd / && \
    cargo new playground
WORKDIR /playground

ADD Cargo.toml /playground/Cargo.toml
RUN cargo build
RUN cargo build --release
RUN rm src/*.rs

All of the downloaded crates are stored in the Docker image’s $HOME/.cargo directory and all of the built crates are stored in the applications target/{debug,release} directories.

Later on, the real source files are copied into the container and cargo build / cargo run can be executed again, using the now-compiled crates.

If you were building an executable project, you’d want to copy in the Cargo.lock as well.

Leave a Comment