December 18, 2015
ES6 Modules and Dependencies with JSPM
The Current Context
To write an ES6 app today, you need a transpiler to convert your ES6 code to ES5. The most popular transpilers are Babel and Traceur. Next, you need a module loader to combine all of the modules into one usable. The module loader you choose depends on which module format you prefer. The most popular choices are RequireJS for AMD, Browserify for CommonJS, and es6-module-loader for ES6 modules. In the end, you will have to minify the code and enable source maps for debugging.
You will also need a way download third party modules. Browserify takes a CommonJS module and transforms it into a browser-understandable version, so the obvious choice for downloading third party modules would be to use NPM. If, on the other hand, you’re using RequireJS, then you can use any package manager and configure Requirejs to find the files you need or you can use a tool like Bower so you don’t have to maintain that configuration. Finally, you can use a task runner like Grunt or Gulp to do all this work for you while writing code.
All in all, you need at least three separate tools: a transpiler, a module loader, and package manager.
It also comes with both Babel and Traceur to transpile your code. You can configure it to use whichever you prefer. Another nice feature of JSPM is it’s ability to download and install third party packages from it’s own repository, npm, or Github.
Let's start by installing it. This is done with npm:
$ npm install -g jspm
After the installation is done, we can initialize our new project. It will prompt you to answer some questions to help you configure the project.
$ jspm init Package.json file does not exist, create it? [yes]: Would you like jspm to prefix the jspm package.json properties under jspm? [yes]: Enter server baseURL (public folder path) [./]: Enter jspm packages folder [./jspm_packages]: Enter config file path [./config.js]: Configuration file config.js doesn't exist, create it? [yes]: Enter client baseURL (public folder URL) [/]: Do you wish to use a transpiler? [yes]: Which ES6 transpiler would you like to use, Babel, TypeScript or Traceur? [babel]:
Now let's install jQuery and load it into our app:
$ jspm install jquery #index.html <!DOCTYPE html> <html> <head> <script src="jspm_packages/system.js"></script> <script src="config.js"></script> <script> System.import('./index.js'); </script> </head> <body> </body> </html> #index.js import $ from 'jquery'; console.log($.fn.jquery)
Now lad index.js in the borwser and open up the console:
JSPM can also bundle our app files:
$ jspm bundle-sfx index.js Building the single-file sfx bundle for index.js... ok Built into build.js with source maps, unminified.
More details on JSPM can be found here.