萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

SeaJS 入門教學:完整模組化開發範例

專案結構

index.html      主頁面
sea.js          SeaJS 核心庫
init.js         入口模組,依賴 data、jquery、style
data.js         純 JSON 資料模組
jquery.js       jQuery 模組化封裝
style.css       樣式模組

index.html

<!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>

data-main="./init" 指定入口模組,SeaJS 會自動載入 init.js。

init.js(入口模組)

define(function(require, exports, module) {
    var $ = require('./jquery');
    var data = require('./data');
    var css = require('./style.css'); // 載入 CSS 模組

    $('.author').html(data.author);
    $('.blog a').attr('href', data.blog);
});

data.js(資料模組)

define({
    author: 'ZhangYang',
    blog: 'https://blog.codinglabs.org'
});

純資料模組可直接 define({...}) 簡寫。

style.css

.author { color: red; font-size: 10pt; }
.blog { font-size: 10pt; }

關鍵觀念

  • 每個檔案即一個模組,define 定義,require 載入。
  • require('./style.css') 會自動將 CSS 插入頁面。
  • data-main 讓 HTML 更乾淨,無需額外 seajs.use()。
copyright © 萬盛學電腦網 all rights reserved