Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an AMD module using require.js

Tags:

requirejs

amd

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.

like image 755
Jasdeep Khalsa Avatar asked Dec 16 '22 15:12

Jasdeep Khalsa


1 Answers

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>
like image 55
asgoth Avatar answered Jan 14 '23 21:01

asgoth