import isFunction from 'lodash/isFunction' ; import { BundleResolver } from './type' ; import { Module , globalModule } from './module' ; import { Record } from './module/Record' ; const getContext = ( id , chunkRecord ) => { let context = chunkRecord . context ; if ( isFunction ( chunkRecord . context ) ) { context = context ( { id } ) ; } return context ; } ; let preHook = null ; /**
 * 在前面加载的模块系统中寻找模块
 */ const findModuleInParent = ( id , resolver ) => { preHook && ! preHook . standalone && preHook ( id , resolver ) ; } ; /**
 * 脚本类型的模块加载，这里是为了那些没导出，但是需要被沙箱 wrap 的脚本
 */ const resolveExternalScript = ( id , resolver , scriptRecord ) => { try { const context = getContext ( id , scriptRecord ) ; resolver . call ( context . window , undefined , undefined , undefined , { ... context } ) ; Module . record . delete ( `${ id }_scripts_` ) ; scriptRecord . loaded = true ; scriptRecord . resolve ( ) ; } catch ( e ) { scriptRecord . reject ( e ) ; } } ; param { string } id param { BundleResolver } resolver export const hook = ( id , resolver ) => { if ( id && resolver ) { const chunkRecord = Module . record . get ( id ) ; const scriptRecord = Module . record . get ( `${ id }_scripts_` ) ; if ( ! chunkRecord && ! scriptRecord ) { return findModuleInParent ( id , resolver ) ; } if ( scriptRecord ) { return resolveExternalScript ( id , resolver , scriptRecord ) ; } if ( ! chunkRecord ) { return ; } const module = globalModule . resolveModule ( id ) ; try { let context = getContext ( id , chunkRecord ) ; if ( chunkRecord . deps ) { Object . entries ( chunkRecord . deps ) . forEach ( ( [ depsName , exports ] ) => { if ( ! exports ) { console . warn ( `${ depsName } is null or undefined, please check the import statement for ${ depsName }` ) ; } const dep = module . resolveModule ( depsName ) ; dep . exports = exports ; } ) ; } module . resolver = resolver ; context = context || globalModule . context ; module . context = context ; resolver ( module . require , module , module . exports , { ... context } ) ; chunkRecord . resolve ( chunkRecord ) ; } catch ( e ) { chunkRecord . reject ( e ) ; } chunkRecord . loaded = true ; } } ; /**
 * inject the global hooks for jsonp loader
 * please use webpack-jsonp-loader-plugin to build bundle
 * code will be wrapped as follow:
 *  window.__CONSOLE_OS_GLOBAL_HOOK__(id, function(require, module, exports, { dependencies }){ / wepback build umd code /})
 */ if ( window . __CONSOLE_OS_GLOBAL_HOOK__ && typeof document !== undefined ) { preHook = window . __CONSOLE_OS_GLOBAL_HOOK__ ; } window . __CONSOLE_OS_GLOBAL_HOOK__ = hook ;