LinusCDE's Blog

Viewing Rust docs live in browser

Published on

When documenting my first rust code, I thought that it would be nice to have the browser window automatically refresh once I hit save.

In the following short tutorial, I’ll show you how.

Overview

  1. Install cargo-watch
  2. Install live-server from pip
  3. Run both

Step 1: Install cargo-watch

First, we need to automatically update the docs in target/doc whenever we change a file.

This can be done with cargo-wacth. To install it for yourself run cargo install cargo-watch.

After that, cargo got a new sub-command called watch. For usage you can either run cargo watch --help or give the project page a visit.

Step 2: Install live-server from pip

So now, we have always updating static files. However unless, we want to refresh the browser ourselves, it would be nice to have some way that the browser does the refresh for us automatically.

There are sure some live-server solutions in the Node world. Since my installation is halve borked however, I looked for another solution.

The pip package live-server does exactly that thing for me. It is a webserver, that serves a given directory, while injecting a JS into every html page that observes the server for any changes and then refreshes itself.

You can install that package either on a user-level or globally.

For a user-level installation you can run pip3 install --user live-server which will install the command/program to ~/.local/bin/ on Linux. You may need to update your PATH-Variable to refrence this path to run the command.

To install it globally you run sudo pip3 install live-server which will install it to /usr/bin/.

Step 3: Run both

Now, that we have all the software, we can combine it 🎶.

Go into your rust project directory and start watching your source code with cargo watch -x doc. Everytime we change something, cargo doc will run and update the docs in target/doc.

Next, we need another terminal. With that we go into the same directory and run live-server target/doc.

Now we should be all set. Just go to localhost:8888/YOUR_CRATE_NAME and the documentation updates a brief moment after you update some source file.

Be sure though to use the crate name and not the project name in the path. So if your project is called “my-lib”, you need to use “my_lib” instead.