淺談前端js面試--開發(fā)環(huán)境-模塊化--requirejs

  • 不使用模塊化
    • util.js getFormatDate函數(shù) 最底層的函數(shù)
    • a-util.js aGetFormatDate 使用依賴getFormatDate (業(yè)務(wù)層的底層)
    • a.js aGetFormatDate (a業(yè)務(wù))一層一層的引用
代碼如下:
// util.js
function getFormatDate(date,type){
    // type === 1 返回 2017-06-15
    // type === 2 返回 2017年06月15日格式
    // ...
}
// a-util.js 
function aGetFormatDate(date){
    //要求返回 2017年6月15日 格式
    return getFormatDate(date,2)
}
// a.js
var dt = new Date()
console.log(aGetFormatDate(dt))
使用
<script src="util.js"></script>
<script src="a-util.js"></script>
<script src="a.js"></script>
<!--1.這些代碼中的函數(shù)必須是全局變量,才能暴露給使用方。全局變量污染-->
<!--2.a.js 知道要引用 a-util.js,但是他知道還需要依賴于util.js嗎?-->
依賴關(guān)系根本不清楚,如果順序錯了,會報錯。
  • 使用模塊化(設(shè)計一種理想狀態(tài),不一定能實現(xiàn))
//util.js
export {
  getFormatDate:function(date,type){
    // type === 1 返回 2017-06-15
    // type === 2 返回 2017年06月15日格式
    // ...
  }
}

// a-util.js
var getFormatDate = require('util.js')
export {
  aGetFormatDate: function(date){
    //要求返回 2017年6月15日 格式
        return getFormatDate(date,2)
  }
}

//a.js
var aGetFormatDate=require('a-util.js')
var dt=new Date()
console.log(aGetFormatDate(dt))
// 直接'<script src="a.js"></script>',其他的根據(jù)依賴關(guān)系自動引用
//那兩個函數(shù),沒必要做成全局變量,不會嗲來污染和覆蓋

AMD

  • require.js requirejs.org/
  • 全局define函數(shù)
  • 全局require函數(shù)
  • 依賴js會自動、異步加載
使用require.js
//util.js
define(
        function() {
            getFormatDate: function(date, type) {
                // type === 1 返回 2017-06-15
                // type === 2 返回 2017年06月15日格式
                // ...
            }
        }
    )
// a-util.js
define(
        [. / util.js],
        function(util) {
            return {
                aGetFormatDate: function(date) {
                    //要求返回 2017年6月15日 格式
                    return getFormatDate(date, 2)
                }
            }
        }
    )
// a.js
define(
        [. / a - util.js],
        function(autil) {
            return {
                printDate: function(date) {
                    console.log(aUtil.aGetFormatDate(date))
                }
            }
        }
    )
// main.js
require(
    ['./a.js'],
    function(a) {
        var date = new Date()
        a.printDate(date);
    }
)
使用
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <link rel="stylesheet" href="">
</head>
<body>
  <script src="./require.min.js" data-main="./main.js"></script>
</body>
</html>

AMD示例
AMD示例

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容