-
Notifications
You must be signed in to change notification settings - Fork 3
Modules
In the Zig language, a module is actually a struct without any fields. Only declarations of constants, variables, and functions. Since the object representing a struct type behaves like a JavaScript class, you can think of declarations within a module as static members.
Zigar exports all public declarations in a module using its own mechanism. You do not need to
use the export
keyword.
When you import a Zig module into JavaScript using ESM syntax, the default export is the module object. Constants and functions (but not variables) are also available as named exports:
const std = @import("std");
pub const pi = std.math.pi;
pub var number: i33 = 123;
pub fn hello() void {
std.debug.print("Hello world", .{});
}
import module, { hello, pi } from './module-example-1.zig';
console.log(module.pi);
console.log(module.number);
module.hello();
hello();
console.log(pi);
3.141592653589793
123n
Hello world
Hello world
3.141592653589793
When CommonJS is used, the object returned by require
is the module.
Destructuring assignment
can be used to extract contants and functions for ease of use:
require('node-zigar/cjs');
const { pi, hello } = require('./module-example-1.zig');
hello();
console.log(pi);
Hello world
3.141592653589793
Since modules are structs, you can make a sub-module available simply by assigning it to a public constant in the root module:
const std = @import("std");
pub const example1 = @import("./module-example-1.zig");
pub const ascii = std.ascii;
import { ascii, example1 } from './module-example-2.zig';
example1.hello();
console.log(ascii.allocUpperString('hello').string);
Hello world
HELLO
The code above exports a module from Zig's standard library. For a variety of reasons, this will
often not work. Many modules contain deprecated declarations, for instance. From the source code
of std.math
:
pub const f16_true_min = @compileError("Deprecated: use `floatTrueMin(f16)` instead");
pub const f32_true_min = @compileError("Deprecated: use `floatTrueMin(f32)` instead");
pub const f64_true_min = @compileError("Deprecated: use `floatTrueMin(f64)` instead");
pub const f80_true_min = @compileError("Deprecated: use `floatTrueMin(f80)` instead");
pub const f128_true_min = @compileError("Deprecated: use `floatTrueMin(f128)` instead");
Attempts to export them would end in a compiler error.