Zig Modules 101: How to Fetch, Add, and Use External Dependencies

Recently, I got access to the Ghostty project, which is written in Zig. I’ve been seeing Zig around for a while, and I wanted to explore it further. So, I decided to build something using Zig and needed to add a module to my project. However, I found that the current documentation on the internet wasn’t perfect, and there were some gaps when it comes to the process of adding dependencies. To save you time, I’m writing my own notes on how to add a module to a Zig project.

In this post, I will walk you through the steps required to add a new module to a Zig project, focusing on how to fetch the module, configure it in the build system, and import it into your project.

Step 1: Fetch the Module

The first thing you need to do is fetch the Zig module that you want to use. You can do this by running the following command:

zig fetch --save <module_url>

Where is the URL of the tarball (a .tar.gz file) containing the Zig code. For example, if the module is hosted on GitHub or any other server, the URL will point directly to the tarball.

What happens behind the scenes?

When you run the above command, Zig will download the tarball, extract it, and save the contents in your project’s zig-modules directory (or the directory where your project is located). Additionally, the build.zig.zon file will be updated with an entry that includes information about this new module. This helps Zig’s build system keep track of external dependencies.

Step 2: Add Dependency in build.zig

Once you’ve fetched the module, the next step is to add it as a dependency in your build.zig file. This is how you tell Zig’s build system about the module you just fetched.

To do this, you need to add the following code to your build.zig file:

const vaxis = b.dependency("vaxis", .{
    .target = target,
    .optimize = optimize,
});

Step 3: Add the Import in the Root Module

The final step is to import the module into your project’s root module. To do this, you need to update the root_module section of your executable.

Here’s how you can add the import:

exe.root_module.addImport("vaxis", vaxis.module("vaxis"));

Step 4: Import the Module in Your Code

Now that you have everything set up, you can import and start using the module in your Zig code. To import the module, use the following simple import statement:

const vaxis = @import("vaxis");

This allows you to access the functionality provided by the vaxis module in your Zig code.

By following these steps, you can easily manage external dependencies in your Zig projects and start integrating them into your codebase. Zig’s build system and import mechanism make it easy to handle modules and dependencies, allowing you to focus on writing your application logic.

If you encounter any issues or have further questions, feel free to create an issue here — repo. Happy coding with Zig!