Gazelle is a tool that generates and updates Bazel build files. You can use it to generate build files when migrating to Bazel, to maintain existing build files, and to import external Go modules that have not been migrated to Bazel.
This example shows how to use Gazelle to generate build files for a small Go program with an external dependency.
To understand how this project works, read these files:
MODULE.bazel
: declares dependencies on Bazel modules, including rules_go and Gazelle.go.mod
: declares dependencies on Go modules. Maintained outside of Bazel with normal Go commands likego mod tidy
.BUILD.bazel
: contains some boilerplate for running Gazelle, as well as targets generated by Gazelle.
To update generated build files, run the command below. This should be done after you add, remove, or rename source files or when you change imports.
bazel run //:gazelle
For example, rename printlinks.go
to print_links.go
, run Gazelle, and observe the change in BUILD.bazel
.
To add a new external dependency:
- Import the external package from any
.go
file. - Run
bazel run @rules_go//go -- mod tidy
. This command runsgo mod tidy
to updatego.mod
using the toolchain downloaded byrules_go
. This command also runsbazel mod tidy
to updateMODULE.bazel
. - Run
bazel run //:gazelle
again to update dependencies inBUILD.bazel
files.