commonJs原理解析

同步加載

  1. 先使用require.register註冊文件路徑和對應方法之間的映射關係保存在require.modules中
  2. 再使用require方法,經過傳入的路徑去require.modules中取出對應的方法
  3. 使用require獲取方法的同時,會觸發依賴模塊中的require方法,這樣就實現了模塊的加載

index.htmlhtml

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <!-- <script src="./commonJS_async.js"></script> -->
    <script src="./commonJS.js"></script>
    <script src="./modules/hello.js"></script>
    <script src="./modules/name.js"></script>
    <script>
        var hello = require("hello.js");
        console.log(hello);
        console.log(require.modules);
        // require.ensure('./modules/ajax.js', function (obj) {
        //     console.log(obj);
        // })
    </script>
</body>
</html>

commonJS.jsajax

function require(path) {
    let mod = require.modules[path];
    mod.exports = {};
    mod.call(window, require, mod, mod.exports);
    return mod.exports;
}

require.modules = {};

require.register = function (path, fn) {
    // 異步加載
    require.modules[path] = fn;
}

hello.js、name.jsapp

//hello.js
require.register('hello.js', function (require, module, exports) {
    let name = require('name.js')
    exports.hello_name = 'hello ' + name;
    exports.hello_world = 'hello world';
})
//name.js
require.register('name.js', function (require, module, exports) {
    module.exports = 'shimingw'
})

異步加載

  1. 異步加載的邏輯匜不復雜,在同步加載的基礎上增長require.ensure方法,預先在modules對象上掛在onload方法
  2. 修改require.register方法,增長異步模塊註冊邏輯,在異步模塊註冊完成後觸發onload,以達到模塊異步加載的需求

commonJS_async.js異步

function require(path) {
    let mod = require.modules[path].method;
    mod.exports = {};
    mod.call(window, require, mod, mod.exports);
    return mod.exports;
}

require.modules = {};

require.register = function (path, fn) {
    // 異步加載
    if (require.modules[path] && require.modules[path].status === 'loading') {
        // 異步加載成功
        require.modules[path].status = 'loaded'
        require.modules[path].method = fn;
        require.modules[path].onload(require(path));
    } else {
        require.modules[path] = {
            moduleName: path, // 模塊Id
            status: 'loaded',
            onload: null,
            method: fn
        };
    }
}

require.ensure = function (path, cb) {
    require.modules[path] = {
        moduleName: path, // 模塊Id
        status: 'loading',
        onload: cb,
        method: null
    };
    var head = document.querySelector('head')
    var script = document.createElement('script');
    script.async = true;
    script.src = path;
    setTimeout(() => {
        head.appendChild(script);
    },5000 );
}
相關文章
相關標籤/搜索