Zo72 Zo72 - 3 months ago 7x
Javascript Question

make my javascript function requirejs/amd friendly?

I have created a javascript library which adds only one global object to the global space.

The global object happens to be a function and the name of the function matches the name of the file.

This is how it looks:

filename: myfunction.js


myfunction = function() {

How do I make my library compliant with amd and require.js ?


The Requirejs Docs tell you all about how to make an AMD compliant module. However, information on how to keep a module working when used without AMD (<script> tag) is hard to find there. Anyway, when in a Requrirejs context, the "define" method is defined. Otherwise, the example below just uses window.x (not the most elegant solution) to expose the function to the global space from within a closure.

(function (module) {
    if (typeof define === "function" && define.amd) {
        define(function () { return module; });
    } else {
        window.myfunction = module.myfunction;
    myfunction: function () {
        /* ... */