Over a million developers have joined DZone.

Writing AMD Modules Using amdefine on Node.js

Download Forrester’s “Vendor Landscape, Application Performance Management” report that examines the evolving role of APM as a key driver of customer satisfaction and business success, brought to you in partnership with BMC.

James Burke’s npm module amdefine lets you write AMD modules [1] that also work on Node.js. To do so, you need to perform the following steps:
  • Install amdefine:
        npm install amdefine
    
    Optional: install into your project by making it a dependency in your package.json.
  • Prefix your AMD with the following line (split into three lines below):
        if (typeof define !== 'function') {
            var define = require('amdefine')(module)
        }
    
    That line will be removed when packaging your AMDs for deployment via the RequireJS optimizer.
The amdefine readme has more information. Writing an AMD in this manner has one disadvantage: To use it on Node.js, one has to install amdefine. Node’s maintainers want to keep the system small and didn’t want to build AMD support in. However, they might reconsider if demand can be proven, by enough people installing amdefine.

If you don’t want to force Node.js users of your module to install amdefine, there are alternatives [2] for writing AMDs that also work on Node.js. But they have other disadvantages.

References:

  1. The power of the Asynchronous Module Definition
  2. Bridging the module gap between Node.js and browsers

See Forrester’s Report, “Vendor Landscape, Application Performance Management” to identify the right vendor to help IT deliver better service at a lower cost, brought to you in partnership with BMC.

Topics:

Published at DZone with permission of Axel Rauschmayer , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}