Javascript 使用 require.js 的简单示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10485039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
simple example for using require.js
提问by Ibrahim
I am trying to learn how to use require.js. So I made an HTML page with the following tags in the body.
我正在尝试学习如何使用 require.js。所以我制作了一个 HTML 页面,在正文中包含以下标签。
<script type="text/javascript" data-main="../js/shirt" src="../js/require.js"></script>
<script type="text/javascript">
alert("Shirt color is " + shirt.color);
</script>
The ../js/shirt.js has the following code
../js/shirt.js 有以下代码
define({
color: "black",
size : "large"
});
How can I use this simple value pairs in my html?
如何在我的 html 中使用这个简单的值对?
采纳答案by Joseph
the contents of the main file should be a require call. for example, you have a values.js module containing:
主文件的内容应该是一个 require 调用。例如,您有一个 values.js 模块,其中包含:
define({
color: "black",
size : "large"
});
in your main file (shirt.js), load the values.js as a dependency (assuming they are in the same directory):
在您的主文件 (shirt.js) 中,加载 values.js 作为依赖项(假设它们在同一目录中):
require(['values'],function(values){
//values.color
//values.size
});
回答by Gabriel Jürgens
In addition to Domenic's answer maybe you prefer this way of using the define function without using require functions inside the modules.
除了 Domenic 的回答之外,也许您更喜欢这种使用 define 函数的方式,而无需在模块内部使用 require 函数。
// shirt.js
define({
color: "black",
size : "large"
});
// logger.js
define(["shirt"], function (shirt) {
return {
logTheShirt: function () {
console.log("color: " + shirt.color + ", size: " + shirt.size);
}
};
});
// main.js
define(["shirt", "logger"],function (shirt, logger) {
alert("Shirt color is: " + shirt.color);
logger.logTheShirt();
});
I prefer this way, but it's only a matter of taste I guess. (I'm assuming that all the scripts are on the same folder.)
我更喜欢这种方式,但我想这只是品味问题。(我假设所有脚本都在同一个文件夹中。)
回答by Domenic
In addition to Joseph's answer, you can also write other modules that depend on shirt
(which is where the real power of RequireJS comes in).
除了 Joseph 的回答,您还可以编写其他依赖的模块shirt
(这就是 RequireJS 的真正威力所在)。
// shirt.js
define({
color: "black",
size : "large"
});
// logger.js
define(function (require) {
var shirt = require("./shirt");
return {
logTheShirt: function () {
console.log("color: " + shirt.color + ", size: " + shirt.size);
}
};
});
// main.js
define(function (require) {
var shirt = require("./shirt");
var logger = require("./logger");
alert("Shirt color is: " + shirt.color);
logger.logTheShirt();
});
Then your HTML can just be
那么你的 HTML 可以是
<script data-main="../js/main" src="../js/require.js"></script>