Intro to Modules
Modules are scripts that are loaded and run within their own namespace. For the most part, you don’t have to worry about how modules work if you are creating a simple Spice script. However, if you wish to write some common classes or functions to share amongst your actions, you’ll need to understand what makes up a module.
Shared modules that you create should be placed in one of these paths (depending on whether your action is a custom user action or part of a Sugar):
Custom user actions
~/Library/Application Support/Espresso/Support/Library/
Sugars
MySugar.sugar/Support/Library/
Modules are loaded using the special require function:
var example = require('example');
If you are creating a module and wish to expose a variable, function, or class within it to scripts that load the module, assign the value to the special exports object:
exports.some_variable = 'My exported variable';
For more information about require, see Global variables.
A module is a Javascript file that is loaded into a generic function and executed. This means that any variables you define at the root of your script will be protected from clashing with other modules because they should never enter the global Javascript namespace. For example, take a file called coffee.js
:
var beans = 100;
var grind_coffee = function() {
beans = beans - 30;
return beans > 0;
}
exports.grind = grind_coffee;
Any module that loads coffee.js will only be able to access grind
; the beans variable is never exposed. For example:
var coffee = require('coffee');
coffee.grind();
// Or alternatively
var grind = require('coffee').grind;
If the above example code happened to have a beans variable of its own, the use of the coffee module would leave the beans variable unaffected. Important note: in order to keep namespaces clean, it’s important to always remember to use var
when initially declaring variables in your modules. Otherwise, the variable may inadvertently end up in the global namespace, which would defeat the purpose of having modules.
Along with require and exports, modules are also provided several other global-scoped objects as described in Global variables.