前面分散講了不少 SeaJS 的概念,這篇直接用一個能跑起來的例子把它們串在一起,方便回頭歸納。
index.html——主頁面sea.js——SeaJS 腳本庫init.js——入口模塊,依賴 data、jquery、style 三個模塊,由主頁面載入data.js——純 JSON 數據模塊,由 init 載入jquery.js——對 jQuery 庫的模塊化封裝,由 init 載入style.css——CSS 樣式表,作為 style 模塊由 init 載入sea.js 和 jquery.js 屬於庫代碼,這裡只列出自己編寫的部分。
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="content">
<p class="author"></p>
<p class="blog"><a href="#">Blog</a></p>
</div>
<script src="./sea.js" data-main="./init"></script>
</body>
</html>
注意最後一行:只引入 sea.js,並通過 data-main 屬性指定入口模塊。這等價於寫 seajs.use('./init'),但讓 HTML 更乾淨。
// init.js —— 入口模塊
define(function (require, exports, module) {
var $ = require('./jquery');
var data = require('./data');
var css = require('./style.css');
$('.author').html(data.author);
$('.blog').attr('href', data.blog);
});
// data.js —— 純數據模塊,直接傳對象給 define
define({
author: 'ZhangYang',
blog: 'https://blog.codinglabs.org'
});
.author { color: red; font-size: 10pt; }
.blog { font-size: 10pt; }
依賴聲明即依賴加載。init.js 裡沒有任何 <script> 標簽,也沒有手動排序,只靠 require 聲明依賴,SeaJS 就會自動按拓撲順序下載 jquery.js、data.js、style.css。頁面只需要關心「我要用什麼」,不用關心「別人什麼時候就緒」。
非 JS 資源也能模塊化。CSS 通過 require('./style.css') 載入,這體現了 SeaJS 「一切皆模塊」的思路。
數據也是模塊。data.js 只 return 一個對象,這種寫法特別適合存放配置和常量。
項目規模一大,這種方式的價值會被放大:新增一個依賴只需在模塊裡加一行 require,不必回到 HTML 裡找插入位置,也不必擔心順序錯了導致某個變量是 undefined。