2 Module
sirius edited this page 2026-10-06 16:47:45 +02:00

A module is a script file that has been loaded in.

The module object

The module object allows a script to

  • Access information about the module, e.g. path of the script file
  • Export values for other modules to use
  • Perform module operations, e.g. import/unimports
  • Specify what to do when the module unloads

In JavaScript (requires jsc/js-runtime), the module object is module, access it with module.path, module.exports, module.import(), module.onunload, etc.

Import/Exports

Behaviour is similar to other scripting languages (e.g. NodeJS), where importing a module returns its exports.

// circles.js
module.exports = {
  pi: 3.14,
  circleArea: function(radius) {
    return 3.14 * radius * radius
  }
};
// index.js
let circles = module.import("./circles.js", []); // don't worry about the empty list for now
circles.circleArea(5);

Warning

Circular import is undefined behaviour, and will become a hard error in the future.

Unimport/unloading

Each module counts the number of files importing it, module.unimport(path) decreases the count of the module at path - when the count reaches 0 the module is immediately unloaded. It will then call unimport on everything it imports, triggering a series of unloads. If the count did not reach 0 after unimport, re-importing it will return the cached exports instead of rerunning the script file.

If the module stores values outside itself (e.g. registering an event listener), it will need to remove them before unloading. Otherwise the value will throw an error when used as it is no longer valid. module.onunload is the cleanup function.

// index.js
let command = newCommand(...);

module.onunload = () => {
  command.unregister();
};

Using import or unimport inside of module.unload will throw an error, do not do that.