Modules
Modules allow you to structure your code into reusable components. They work similarly to JavaScript modules but come with stricter rules, such as only allowing exports from the global scope and treating circular dependencies as errors.
Importing and Exporting
You can export variables and functions from a module, but only if they are declared in the global scope.
Exporting from a Module
// myModule.var
export const value = 42;
export fn greet() {
return "Hello!";
}
Importing from a Module
To import a value or function, use the following syntax:
import value from "myModule.var";
import greet from "myModule.var";
// Or alternatively
import value, greet from "myModule.var";
console.log(value); // 42
console.log(greet()); // "Hello!"
You can also navigate relative directories when importing:
import data from "utils/helper.var"; // From a subdirectory
import config from "../config.var"; // Going up one directory
Circular Dependencies
Circular dependencies occur when two or more modules depend on each other, either directly or indirectly. In Varjus, such cases are treated as errors to prevent unpredictable behavior.
Example of a Circular Dependency
// moduleA.var
import b from "moduleB.var";
export const a = 10;
// moduleB.var
import a from "moduleA.var";
export const b = 20;
Attempting to run this code will result in an error due to the circular dependency.
⚠️ Circular dependencies are not allowed. Ensure that module dependencies are structured in a way that avoids cyclic imports.
Modules help keep your code organized and maintainable while ensuring clear dependency structures.