Set up wasm-pack dev shell in Nix?

I want to set up a dev shell for running wasm-pack, and I have this flake right now:

{
  description = "wasm-pack setup";

  inputs = {
    nixpkgs = { url = "github:nixos/nixpkgs/nixos-unstable"; };
    rust-overlay = { url = "github:oxalica/rust-overlay"; };
  };

  outputs = { nixpkgs, rust-overlay, ... }:
    let system = "x86_64-linux";
    in {
      devShell.${system} = let
        overlay = [ (import rust-overlay) ];
        pkgs = import nixpkgs { inherit system overlay; };
      in (({ pkgs, ... }:
        pkgs.mkShell {
          buildInputs = with pkgs; [
            rustc
            cargo
            nodejs
            wasm-pack
          ];

          shellHook = "";
        }) { pkgs = pkgs; });
    };
}

Then I run wasm-pack new foo, cd foo, wasm-pack build, and I got this error:

Error: wasm32-unknown-unknown target not found in sysroot: "/nix/store/sw7kr9clh3y3rpghgh50j023nbnwqz9i-rustc-1.55.0"

Used rustc from the following path: "/nix/store/sw7kr9clh3y3rpghgh50j023nbnwqz9i-rustc-1.55.0/bin/rustc"
It looks like Rustup is not being used. For non-Rustup setups, the wasm32-unknown-unknown target needs to be installed manually. See https://rustwasm.github.io/wasm-pack/book/prerequisites/non-rustup-setups.html on how to do this.

I have found someone with similar issue in this gist, but I cannot find an obvious solution yet:

So how can I set the target correctly?

1 Like

I skimmed this quickly and it looks like you’ll need to manually add the target.
Someone using oxalica’s overlay demonstrates how you can override the Rust toolchain and add a target:

2 Likes

Thanks! I am able to use that example, add that target, and it worked!

{
  description = "wasm-pack setup";

  inputs = {
    nixpkgs = { url = "github:nixos/nixpkgs/nixos-unstable"; };
    rust-overlay = { url = "github:oxalica/rust-overlay"; };
  };

  outputs = { nixpkgs, rust-overlay, ... }:
    let system = "x86_64-linux";
    in {
      devShell.${system} = let
        pkgs = import nixpkgs {
          inherit system;
          overlays = [ rust-overlay.overlay ];
        };
      in (({ pkgs, ... }:
        pkgs.mkShell {
          buildInputs = with pkgs; [
            cargo
            nodejs
            wasm-pack
            (rust-bin.stable.latest.default.override {
              extensions = [ "rust-src" ];
              targets = [ "wasm32-unknown-unknown" ];
            })
          ];

          shellHook = "";
        }) { pkgs = pkgs; });
    };
}
2 Likes