SeaJS 模塊化加載框架使用


SeaJS 是一個遵循 CMD 規范的模塊化加載框架

CommonJS,CMD,AMD等規范后文會提到,這里主要先了解如何在代碼中使用。

 

如果你有使用過nodejs ,那么理解起來就容易多了。

 

我們通過sea.js來加載我們定義的模塊(這會兒遵循CMD規范)並使用相應的數據。

首先,當然是要下載sea.js,可以直接去 http://seajs.org/docs/#downloads 直接下載代碼包,解壓后 在 /dist/目錄下可以 找到 sea.js

CMD規范是懶加載,按需加載,也就是在require的時候相應的模塊才會被加載進來。

基本用法為:

define(function(require, exports, module) {

  // The module code goes here
 // require ..
});

CMD詳細用法見此

 

舉個例子:(為了簡單說明,暫時先直接置於同一目錄)

index.html是主界面,main.js這里充當了主模塊文件(一般需要 seajs.use('.main') 的方式來加載主模塊),然后主模塊main又調用main1,main2小模塊,理解執行過程。

 

index.html:

首先包含資源sea.js ,再包含主模塊,這里因為要執行主模塊中返回的數據,所以使用了回調函數的處理

<!DOCTYPE html>
<html>
<head>
    <title>Seajs</title>
    <style type="text/css">
    </style>
</head>
<body>

<script type="text/javascript" src="./sea.js"></script>
<script type="text/javascript">
//加載入口文件main.js,默認后綴js自動匹配
    seajs.use('./main',function(main){ 
        console.log(main.say());
    });
</script>
</body>
</html>

main.js:

這里,main.js定義了一個模塊main.js ,在其中又require其他模塊進行處理,然后返回一個對象。

返回的時候可以直接使用return,類型會自動判斷,也可以module.exports = 

比如想返回 ‘w' ,可以直接 return ’w'; 或 module.exports = 'w'; index那里相應做一下修改就行。

define(function(require,exports,module){ 
    console.log('module of main:');
    var main1 = require('main1');
    main1.say();
    var main2 = require('main2');
    main2.say();

    return { 
        say: function(){ 
            console.log('main--hello');
        }
    };

});

main1.js:

define(function(require,exports,module){ 
    console.log('module of main1:');

    module.exports = { 
        say: function(){ 
            console.log('main1--hello');
        }
    };
});

 

main2.js:

define(function(require,exports,module){ 
    console.log('module of main2:');

    return { 
        say: function(){ 
            console.log('main2--hello');
        }
    };
});

 

ok 瀏覽器訪問index.html 即可看到執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM