嵌套依赖项的 Hello World
以下示例通过使用 define() 函数演示多个依赖项来扩展 Hello World。
创建一个名为 index.html 的新 HTML 文件并粘贴以下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello RequireJS</title>
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
</head>
<body>
<!-- place content here --->
<script>
requirejs(["scripts/say"], function(say) {
console.log(say.hello("english"));
console.log(say.hello("spanish"));
console.log(say.hello("french"));
});
</script>
</body>
在 scripts/say.js 创建一个新的 JS 文件并粘贴以下内容:
define(["scripts/translations"], function(translations){
return {
hello: function(language){
return translations[language].hello + " " + translations[language].world;
}
};
});
在 scripts/translations.js 创建一个新的 JS 文件并粘贴以下内容:
define([], function(){
return {
"english": {
hello: "Hello",
world: "World"
},
"spanish": {
hello: "Hola",
world: "Mundo"
},
"french": {
hello: "Bonjour",
world: "Le Monde"
}
};
});
你的项目结构应如下所示:
- project
- index.html
- scripts
- say.js
- translations.js
在浏览器中打开 index.html 文件,控制台将输出:
Hello World
Hola Mundo
Bonjour Le Monde
说明
-
加载 require.js 脚本文件。
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script> -
从
scripts文件夹异步加载say模块。 (请注意,引用模块时不需要.js扩展。) 然后将返回的模块传递给提供hello()的函数。<script> requirejs(["scripts/say"], function(say) { console.log(say.hello("english")); console.log(say.hello("spanish")); console.log(say.hello("french")); }); </script> -
say模块返回一个对象,其中定义了一个函数hello,但在这种情况下,我们定义了一个依赖项(scripts/translations),我们将从那里拉出翻译。define(["scripts/translations"], function(translations){ return { hello: function(language){ return translations[language].hello + " " + translations[language].world; } }; }); -
translations模块只返回具有各种单词翻译的对象。define([], function(){ return { "english": { hello: "Hello", world: "World" }, "spanish": { hello: "Hola", world: "Mundo" }, "french": { hello: "Bonjour", world: "Le Monde" } }; });