使用require.js创建AMD模块

Jas*_*lsa 4 amd requirejs

我有以下功能:

function(){
    add: function(x, y){
        return console.log(x + y);
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何define()将此作为AMD(异步模块定义)兼容模块使用require.js,然后在浏览器中使用它?

我正在寻找一个专门用于jsfiddle显示它直接在浏览器中工作的示例.

asg*_*oth 12

如果没有依赖:

test.js:

define(function(){
    return {
       add: function(x, y){
           return console.log(x + y);
       }
    };
});
Run Code Online (Sandbox Code Playgroud)

有依赖关系

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

以下是require的示例.

要引用该模块,请使用require:

bootstrap.js:

/*global define, require */

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

    test.add(4, 5);
});
Run Code Online (Sandbox Code Playgroud)

我的文件夹结构:

  • root(又名公共)
    • JS
      • bootstrap.js
      • test.js
    • LIB
      • 要求
        • require.js
    • 的index.html

在html页面中(在jade中,类似于html):

<body>
    ...
    <script type="text/javascript" src="lib/require/require.js" data-main="js/bootstrap"></script>
</body>
Run Code Online (Sandbox Code Playgroud)