Package manager

Package manager

Zig package manager

Since 0.11, Zig has now an official built-in package manager that uses files with the .zig.zon extension.

There is no global repository like crates.io(Rust) or npmjs(Node.js) for Zig packages. Instead, Zig packages are distributed as git repositories.

In order to add packages to your project you are going to create and edit a file in the root of your project named "build.zig.zon" (zon stands for Zig Object Notation, which is an equivalent to json).

Add a package in your project

  1. Add the packages you want in your build.zig.zon file
  .{
      .name = "name-of-my-project",
      .version = "0.0.1",
  
      .dependencies = .{
          // Here you add all the packages you want, in this exemple I have imported zap which is a web framework
          .zap = .{
              .url = "https://github.com/zigzap/zap/archive/refs/tags/v0.1.7-pre.tar.gz",
              .hash = "1220002d24d73672fe8b1e39717c0671598acc8ec27b8af2e1caf623a4fd0ce0d1bd",
          },
      }
  }

You can get further understanding in how to write your build.zig.zon following the official doc: https://github.com/ziglang/zig/blob/master/doc/build.zig.zon.md

With 0.12.0 you can now use the "zig fetch" command from the root of your zig project to fetch the packages you need:

  zig fetch --save git+https://github.com/zigzap/zap/#HEAD

If you are prior to 0.12.0, you can write the "url" parameter without the "hash", then "zig build" and the outpout will give you the correct hash that you can then put back in your build.zig.zon file.

  1. Add those added packages in your build.zig

Simply add the following code after the "addExectuable" function

  const zap = b.dependency("zap", .{
          .target = target,
          .optimize = optimize,
  });
  // exe.addModule("zap", zap.module("zap")); // If you are using < 0.12.0
  exe.root_module.addImport("zap", zap.module("zap"));
  exe.linkLibrary(zap.artifact("facil.io")); // Specific to zap

Note: here it is specific to the zap package, you might have different options and no need to link a library for an other package (zap uses facil.io under the hood)

  1. Simply "@import" them and use them in your code :)
  const zap = @import("zap");

Your packages will be downloaded and compiled when you build your project.

When importing projects be really careful about your Zig version is and what version is the library you are using compatible with. Zig versions are moving really fast and often are not compatible with previous versions.