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' })
require.ensure
方法,預先在modules
對象上掛在onload
方法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 ); }