Sometimes configure
(or Gazelle) isn’t sufficient for creating BUILD
files, so Bazel users must understand the contents enough to read and edit them manually.
Editor extensions
Your editor or IDE may have a Bazel plugin you can install. This plugin highlights syntax in BUILD
files and possibly offers other features, such as building targets. These plugins do not have auto-completion yet, though a Starlark Language Service is available in the Buck ecosystem and may eventually become part of Bazel.
Starlark
Starlark is a Python-ish language used by Bazel, Buck, tilt, and many other tools. There are Java, Go, and Rust implementations of the interpreter.
The spec is surprisingly readable and explains how the execution model is guaranteed to allow parallel evaluation. Read: https://github.com/bazelbuild/starlark/blob/master/spec.md
BUILD.bazel
files are written in a restricted subset of Starlark.
Bazel extensions, written in *.bzl
files, use the full Starlark language.
load
statements
load
statements should appear at the top of the file. They import symbols into file scope and are eagerly evaluated.
The first argument is a label of a .bzl
source file, and the following arguments are symbols to load.
load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files")
write_source_files(...)
You can alias a symbol on load, which sometimes needed to avoid collisions:
load("@npm//:typescript/package_json.bzl", typescript_bin = "bin")
typescript_bin(...)
package
statement
Optionally, you can define defaults for all targets in the BUILD
file:
package(default_visibility = ["//visibility:public"])
glob
function
The glob
function allows you to skip listing individual files, for example:
srcs = glob(["*.ts"])
.
However, the glob must be evaluated every time Bazel loads the file, and so it incurs a performance penalty, especially as the number of files in the package grows.
It also doesn't descend into sub-packages, so it's easy to omit files by accident.
Here’s a talk about glob from BazelCon 2024: https://www.youtube.com/watch?v=ZrevTeuU-gQ&list=PLbzoR-pLrL6ptKfAQNZ5RS4HMdmeilBcw&index=26