How can I build Rust to WASM with buildRustPackage?

I’m sorry in advance if this is a basic question, but I can’t figure out how to write a nix flake that outputs my Rust library as WASM.

I started with nix flake init --template "github:DeterminateSystems/zero-to-nix#rust-pkg" from this guide (flake.nix pasted below). But I don’t know how to target WASM with buildRustPackage, along the lines of cargo build --target=wasm32-unknown-unknown.

After searching about online, I found that there was a package in nixpkgs called rustc-wasm32, which then got merged with rustc, so I presume the rust compiler I have supports targeting wasm32-unknown-unknown. I think I need to do something like cross-compilation, but I’m not sure.

If there is something else I should be using instead of buildRustPackage, I’d also be interested to know about that. Thank you!


flake.nix

{
  description = "Rust example flake for Zero to Nix";

  inputs = {
    nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.2305.491812.tar.gz";
    # Provides helpers for Rust toolchains
    rust-overlay.url = "github:oxalica/rust-overlay";
  };

  outputs = { self, nixpkgs, rust-overlay }:
    let
      # Systems supported
      allSystems = [
        "x86_64-linux" # 64-bit Intel/AMD Linux
        "aarch64-linux" # 64-bit ARM Linux
        "x86_64-darwin" # 64-bit Intel macOS
        "aarch64-darwin" # 64-bit ARM macOS
      ];

      # Helper to provide system-specific attributes
      forAllSystems = f: nixpkgs.lib.genAttrs allSystems (system: f {
        pkgs = import nixpkgs {
          inherit system;
          overlays = [
            # Provides Nixpkgs with a rust-bin attribute for building Rust toolchains
            rust-overlay.overlays.default
            # Uses the rust-bin attribute to select a Rust toolchain
            self.overlays.default
          ];
        };
      });
    in
    {
      overlays.default = final: prev: {
        # The Rust toolchain used for the package build
        rustToolchain = final.rust-bin.stable.latest.default;
      };

      packages = forAllSystems ({ pkgs }: {
        default =
          let
            rustPlatform = pkgs.makeRustPlatform {
              cargo = pkgs.rustToolchain;
              rustc = pkgs.rustToolchain;
            };
          in
          rustPlatform.buildRustPackage {
            name = "zero-to-nix-rust";
            src = ./.;
            cargoLock = {
              lockFile = ./Cargo.lock;
            };
          };
      });
    };
}
3 Likes