Hello World
以下示例將演示 RequireJS 的基本安裝和設定。
建立一個名為 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) {
alert(say.hello());
});
</script>
</body>
在 scripts/say.js 建立一個新的 JS 檔案並貼上以下內容:
define([], function(){
return {
hello: function(){
return "Hello World";
}
};
});
你的專案結構應如下所示:
- project
- index.html
- scripts
- say.js
在瀏覽器中開啟 index.html 檔案,它會以 Hello World 提醒你。
說明
-
載入 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) { alert(say.hello()); }); </script> -
say模組返回一個物件,其中定義了一個函式hello。define([], function(){ return { hello: function(){ return "Hello World"; } }; });