Webpack运行时require能力解析

Webpack构建好的js文件中,我们可以看到其实现的简版模块加载方式,__webpack_require__是我们很容易猜到功能,约等于import能力,可以加载某模块。 我们的各种模块化加载语法最后都会变成__webpack_require__来加载。

__webpack_require__函数

 // The require function
 function __webpack_require__(moduleId) {

 	// 检测是否存在缓存
 	if(installedModules[moduleId]) {
 		return installedModules[moduleId].exports;
 	}
 	// 不存在则生成新的模块
 	var module = installedModules[moduleId] = {
 		i: moduleId,
 		l: false,    // 是否加载
 		exports: {}
 	};

 	// call的方式加载模块 this转交,参数转交,对应其打包构建好的每个模块的参数结构。
 	modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

 	// 表示已加载
 	module.l = true;

 	// 返回模块的exports 
 	return module.exports;
 }
复制代码

__webpack_require__各属性

以下是__webpack_require__各属性以及对应能力,会经常出现在加载模块的语法中,可以帮助我们加深对__webpack_require__的理解。

// 入口模块的ID
__webpack_require__.s = the module id of the entry point

//模块缓存对象 {} id:{ exports /id/loaded}
__webpack_require__.c = the module cache

// 所有构建生成的模块 []
__webpack_require__.m = the module functions

// 公共路径,为所有资源指定一个基础路径
__webpack_require__.p = the bundle public path
// 
__webpack_require__.i = the identity function used for harmony imports

// 异步模块加载函数,如果没有再缓存模块中 则用jsonscriptsrc 加载  
__webpack_require__.e = the chunk ensure function

// 设定getter 辅助函数而已
__webpack_require__.d = the exported property define getter function

// 辅助函数而已 Object.prototype.hasOwnProperty.call
__webpack_require__.o = Object.prototype.hasOwnProperty.call

// 给exports设定attr __esModule
__webpack_require__.r = define compatibility on export

// 用于取值,伪造namespace
__webpack_require__.t = create a fake namespace object

// 用于兼容性取值(esmodule 取default, 非esmodule 直接返回module)
__webpack_require__.n = compatibility get default export

// hash
__webpack_require__.h = the webpack hash

// 
__webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id

// 异步加载失败处理函数 辅助函数而已
__webpack_require__.oe = the uncaught error handler for the webpack runtime

// 表明脚本需要安全加载 CSP策略
__webpack_require__.nc = the script nonce

复制代码

以上只是完成了基本的__webpack_require__认识。后续还要结合runtime的其它源码一起解读Webpack

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值