For host environments like the web browser and nodejs, build as a library using the freestanding OS target. Here’s an example of running Zig code compiled to WebAssembly with nodejs.

    test.js

    1. const fs = require('fs');
    2. const source = fs.readFileSync("./math.wasm");
    3. const typedArray = new Uint8Array(source);
    4. WebAssembly.instantiate(typedArray, {
    5. env: {
    6. print: (result) => { console.log(`The result is ${result}`); }
    7. }}).then(result => {
    8. const add = result.instance.exports.add;
    9. add(1, 2);
    10. });

    WASI

    args.zig

    1. var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
    2. const gpa = &general_purpose_allocator.allocator;
    3. const args = try std.process.argsAlloc(gpa);
    4. defer std.process.argsFree(gpa, args);
    5. for (args) |arg, i| {
    6. std.debug.print("{}: {}\n", .{ i, arg });
    7. }
    8. }
    1. $ zig build-exe args.zig -target wasm32-wasi

    preopens.zig

    1. const std = @import("std");
    2. const PreopenList = std.fs.wasi.PreopenList;
    3. pub fn main() !void {
    4. var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
    5. const gpa = &general_purpose_allocator.allocator;
    6. var preopens = PreopenList.init(gpa);
    7. defer preopens.deinit();
    8. try preopens.populate();
    9. for (preopens.asSlice()) |preopen, i| {
    10. std.debug.print("{}: {}\n", .{ i, preopen });
    11. }
    12. }