module 'math' { export function sum(x, y) { return x + y; } export var pi = 3.141593; }
// we can import in script code, not just inside a module import {sum, pi} from 'math'; alert("2π = " + sum(pi, pi));
// a static module reference module Math from 'math'; // reify M as an immutable "module instance object" alert("2π = " + Math.sum(Math.pi, Math.pi));
import { draw as drawShape } from 'shape'; import { draw as drawGun } from 'cowboy'; ...
The common idiom for organizing modules in a package or library is by hierarchies separated by ‘/’. The browser loader treats this as the standard structure.
module 'widgets' { ... } module 'widgets/button' { ... } module 'widgets/alert' { ... } module 'widgets/textarea' { ... } import { messageBox, confirmDialog } from 'widgets/alert'; ...
// loading from a URL module JSON from 'http://json.org/modules/json2.js'; alert(JSON.stringify({'hi': 'world'}));
// loading from a URL providing sub-modules module YUI from 'http://developer.yahoo.com/modules/yui3.js'; alert(YUI.dom.Color.toHex(“blue”));
// easy! module 'Even' { import odd from 'Odd'; export default function even(n) { return n == 0 || odd(n - 1); } } // woo-hoo! module 'Odd' { import even from 'Even'; export default function odd(n) { return n != 0 && even(n - 1); } }
System.load('http://json.org/modules/json2.js', function(JSON) { alert(JSON.stringify([0, {a: true}])); });
module 'DOMMunger' { // parameterized by a DOM implementation export function make(domAPI) { return { munge: function(doc) { ... domAPI.alert('hi!'); ... } }; } }
module 'SafeDOM' { import { alert } from 'DOM'; export let document = { write: function(txt) { alert('I\'m sorry, Dave, I\'m afraid I can\'t do that...') }, ... }; }
module DOMMunger from 'DOMMunger'; module SafeDOM from 'SafeDOM'; var instance = DOMMunger.make(SafeDOM); instance.munge(...);
module 'counter' { var n = 0; export function increment() { return n++ } export function current() { return n } }
In a server-side JS environment’s default System loader, module names might map to filesystem paths.
// io/File.js export function open(path) { ... }; export function close(hnd) { ... }; ...
// compiler/Lexer.js import { open, close } from 'io/File'; export function scan(in) { try { var h = open(in) ... } finally { close(h) } }
module lexer from 'compiler/Lexer'; module shell from 'shell'; ... lexer.scan(shell.cmdline[0]) ...