O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Module Loaders

To use CommonJS modules on the client side, we need to use a module loader library. There is a variety of options, each with its own strengths and weaknesses. I’ll cover the most popular ones and you can choose which one best suits your needs.

The CommonJS module format is still in flux, with various proposals under review. As it stands, there’s no officially blessed transport format, which unfortunately complicates things. The two main module implementations in the wild are Transport C and Transport D. If you use any of the wrapping tools mentioned in the sections below, you’ll have to make sure it generates wrapped modules in a format your loader supports. Fortunately, many module loaders also come with compatible wrapping tools, or they specify supported ones in their documentation.

Yabble

Yabble is an excellent and lightweight module loader. You can configure Yabble to either request modules with XHR or to use script tags. The advantage to fetching modules with XHR is that they don’t need wrapping in the transport format. However, the disadvantage is that modules have to be executed using eval(), making debugging more difficult. Additionally, there are cross-domain issues, especially if you’re using a CDN. Ideally, you should only use the XHR option for quick and dirty development, certainly not in production:

<script src="https://github.com/jbrantly/yabble/raw/master/lib/yabble.js"> </script> <script> require.setModuleRoot("javascripts"); // We can use script tags ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required