Using jspm to handle JavaScript modules

jspm is a package manager for JavaScript applications relying on SystemJS.
SystemJS is a universal dynamic module loader, capable of loading any module format such as CommonJS, AMD, ES6 and even modules that export a global variable.


Setup of jspm

I recommend to install jspm as a global tool through npm:

npm intall -g jspm  
Setup of a project

Create a folder for the project then run:

jspm install  

It will create a config.js which contains the configuration of the modules in the project and a package.json which stores the dependencies of the project under the jspm key.
It will also download some libraries that jspm needs (SystemJS, Traceur and Traceur runtime).

Setup of an application

We need an entry point to load required scripts, let's add an index.html:

<!DOCTYPE html>  
<html>  
  <head>
    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script>
      System.import('./app');
    </script>
  </head>
  <body>
  </body>
</html>  

We load SystemJS, then config.js. We are then able to import, through System.import1, app.js which is the root module of the application.

1System.import is an API to load ES6 modules, polyfilled by SystemJS.

Let's add now a very simple app.js:

console.log('app is loaded');  
Setup of dependencies

Let's install some dependencies to see jspm in action. We can install them from github, npm or the small, yet useful, jspm registry.

From jspm registry

jspm install jquery  

jspm will update package.json, so jquery will be installed and config.js to tell SystemJS how to resolve the module when requested.

From npm

jspm install lodash=npm:lodash  

The command is slightly different as we tell jspm to map lodash key to npm lodash module (we are not forced to use an alias but using lodash is more user-friendly than npm:lodash).

From github

jspm install moment=github:moment/moment  
Module usage within the application

Let's update app.js to use our modules:

import $ from 'jquery';  
import _ from 'lodash';  
import moment from 'moment';

console.log('app is loaded');  
console.log(`jquery@${$.fn.jquery} is loaded`);  
console.log(`lodash@${_.VERSION} is loaded`);  
console.log(`moment@${moment.version} is loaded`);  

There are other package managers and I used intensively 2 of them (RequireJS and Browserify) but I prefer jspm at the end.
With RequireJS, I need an external tool, like Bower, to install modules and I need to manually manage mappings and namings.
With Browserify, I need to have a build workflow that is running everytime a file is changed. Traceur compiles our ES6 files directly in the browser for us.

Hope you enjoyed reading this article !