In Jetpack, Every Extension is an Island

Ahoy Castaway!

The Jetpack SDK relies on a few key concepts that allow it to be extremely modular and collaborative. To understand this more clearly, let’s think about the environment it provides to add-ons as an island – yes, like the Tom Hanks hand-print-on-volleyball kind.

Initially the island (a nearly-empty JavaScript execution environment) is a pretty lonely place. All you have on your island to start is the code you’ve written in your main.js file and a few globals – here’s a simple visual:

The empty island environment of Jetpack

Making your island more fun

Now that you’re familiar with the basics of Jetpack and the environment in which your code is executed, you’re probably thinking “I need more than that to write a powerful add-on dude! Not to fear, this is exactly what the CommonJS Modules implementation inside Jetpack is for.

CommonJS modules are JavaScript files that provide useful functionality, including access to the Mozilla platform and Firefox features. Whether they are part of the standard Jetpack API or a third-party library, modules expose functionality via their exports object, which you can import into your execution environment with the require statement. Here’s an example that shows both parts of the process:

Creating and exporting module functionality:
function Bar(options) {
     //Do some foo-ish stuff here
}

exports.Bar = Bar;  //Now export that Foo!
Importing module functionality with require:
//Inside your add-on's main.js file
var myBar = require('Foo').Bar

Think of the functionality you receive from using the require statement as a useful package that is dropped onto your island from the module that is being required. Each of the modules you include in your code are executed in a separate JavaScript execution environment of their own; these separate JavaScript contexts start out with the same set of constraints as your main.js context.

It is also important to note that all modules in Jetpack have their own global object, so when a module uses “this” outside a method call, it is referring to that module’s own global object rather than the global object of the main.js file that required it (unlike on the web, where all JavaScript files you load into a web page share the same global object).

Here’s a graphical representation to help conceptualize the modular system within Jetpack:

Understanding modules in Jetpack

Jetpack SDK was purposefully built in a way that promotes collaborative community coding and rapid browser innovation. Our goal is to create an expansive and vibrant repository of community-generated APIs and custom libraries that will do for the browser what JavaScript libraries like jQuery, MooTools, and Prototype have done for the web, so get involved and help us get there!

– Daniel Buchner, on behalf of the Jetpack team