Requirejs 使用require.js创建AMD模块
我有以下功能:Requirejs 使用require.js创建AMD模块,requirejs,amd,Requirejs,Amd,我有以下功能: function(){ add: function(x, y){ return console.log(x + y); } } 如何使用require.js将()定义为AMD(异步模块定义)兼容模块,然后在浏览器中使用它 我特别寻找一个使用jsfiddle直接在浏览器中运行的示例。如果没有依赖项: test.js: define(function(){ return { add: function(x, y){
function(){
add: function(x, y){
return console.log(x + y);
}
}
如何使用require.js
将()定义为AMD(异步模块定义)兼容模块,然后在浏览器中使用它
我特别寻找一个使用jsfiddle
直接在浏览器中运行的示例。如果没有依赖项:
test.js:
define(function(){
return {
add: function(x, y){
return console.log(x + y);
}
};
});
/*global define, require */
require.config({
baseUrl: 'js'
});
require(['test'], function (test) {
'use strict';
test.add(4, 5);
});
有依赖关系
define(['dep1', 'dep2'], function(dep1, dep2) {
return {
add: function(x, y){
return console.log(x + y);
}
};
});
下面是一个例子
要参考该模块,请使用require:
bootstrap.js:
define(function(){
return {
add: function(x, y){
return console.log(x + y);
}
};
});
/*global define, require */
require.config({
baseUrl: 'js'
});
require(['test'], function (test) {
'use strict';
test.add(4, 5);
});
我的文件夹结构:
- 根(又名公共)
- js
- bootstrap.js
- test.js
- 解放党
- 要求
- require.js
- 要求
- index.html
- js
...
在浏览器中直接定义AMD模块时,该模块不能是匿名的,它必须有名称,否则require.js
将抛出错误未捕获错误:不匹配的匿名定义()模块
如果您使用的是r.js优化器,则可以定义匿名AMD模块,并且r.js将负责模块名称。这是为了避免模块名称冲突而设计的
// 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);
});
以下是示例代码。您可能需要检查语法,了解示例代码语法有何问题?与其回答说您宁愿复制粘贴到jsbin.com,例如,自己看看如果我尝试在JSFIDLE中运行您的第一个示例,
require.js
给出错误未捕获错误:不匹配的匿名定义()模块
?由于引用,您的代码仍然在JSFIDLE中抛出错误。如果您看到我上面的答案,如果您直接在web上定义一个模块,它不能是匿名的,它需要有一个名称:)非常奇怪,因为我在我的本地web服务器(而不是JSFIDLE)上尝试过它。您的文件夹/文件结构是什么样的?我无法让它在我的本地网站上运行。是的,可以:)谢谢你的澄清。我认为这不能在线工作的唯一原因是JSFIDLE不将示例存储为文件,而requirejs为匿名模块寻找文件结构