Duktape has a built-in minimal module loading framework based on
CommonJS modules version 1.1.1,
with additional support for module.exports
and a few Duktape
specific module
object properties.
The internals are documented in
modules.rst.
A recommended (but not mandatory) C module convention is described in
c-module-convention.rst.
You can load modules from Ecmascript code with the global require()
function:
var mod = require('foo/bar'); mod.hello();
Modules are defined by Ecmascript code running in a special environment
defined by the CommonJS modules specification. Inside this environment,
variable/function declarations are local to the module and don't affect the
global object. The environment also provides three special symbols related
to module loading: exports
for exporting module symbols,
module
for providing module metadata (module.id
in particular), and require()
for loading further modules with
relative module identifiers resolved in the context of the current module.
Example:
// foo/bar.js var text = 'Hello world!'; // not visible outside the module var quux = require('./quux'); // loads foo/quux exports.hello = function () { print(text); };
Duktape supports module.exports
(as of Duktape 1.3) so that
you can write modules like:
// foo/bar.js module.exports = function adder(x, y) { return x + y; }; // main.js var adder = require('foo/bar'); print('2 + 3 = ' + adder(2, 3));
Because Duktape is embeddable and portable to different environments there
is no standard way to search for modules. User code must provide a module
search function in Duktape.modSearch
for module loading to work.
The module search function essentially maps a module identifier to the source
code of the module (see below for more details). Example:
// See module search function details below. Duktape.modSearch = function (id) { print('loading module:', id); // Return source code for module or throw an error. };
See How to use modules for examples.