4
votes

I have the following function:

function(){
    add: function(x, y){
        return console.log(x + y);
    }
}

How do I define() this as an AMD (Asynchronous Module Definition) compatible module using require.js and then use it in the browser?

I'm looking specially for an example using jsfiddle to show it works in the browser directly.

2
You might want to check your syntax for the example codeSimon Smith
What's wrong with the syntax?Jasdeep Khalsa
Instead of replying that you'd rather copy paste it in jsbin.com, e.g., and see for yourselfdrodsou

2 Answers

12
votes

If no dependencies:

test.js:

define(function(){
    return {
       add: function(x, y){
           return console.log(x + y);
       }
    };
});

With dependencies

define(['dep1', 'dep2'], function(dep1, dep2) {
    return {
       add: function(x, y){
           return console.log(x + y);
       }
    };
});

Here is a example with require.

To reference the module, use require:

bootstrap.js:

/*global define, require */

require.config({
    baseUrl: 'js'
});
require(['test'], function (test) {
    'use strict';

    test.add(4, 5);
});

My folder structure:

  • root (aka public)
    • js
      • bootstrap.js
      • test.js
    • lib
      • require
        • require.js
    • index.html

In the html page (in jade, similar in html):

<body>
    ...
    <script type="text/javascript" src="lib/require/require.js" data-main="js/bootstrap"></script>
</body>
0
votes

When directly defining an AMD module in a browser, the module cannot be anonymous, it must have a name otherwise require.js will throw the error Uncaught Error: Mismatched anonymous define() module.

If you are using the r.js optimizer you can define anonymous AMD modules and r.js will look after module names. This is designed to avoid conflicting module names.

// Define a module (export)
define('a', {
    add: function(x, y){
         return console.log(x + y);
     }
});

// Use the module (import)
require(['a'], function(a){
    a.add(1, 2);
});

require(['a'], function(a){
    a.add(4, 6);
});

Here is the jsfiddle example.