剖析webpack模块化原理

创建项目

先创建一个最简单的项目,之后用webpack打包,然后分析打包之后的代码。

app.js入口文件

import('./a').then(a=>{
    console.log('成功加载a.js文件');
    a();
})

a.js 文件

import b from './b.js';
function a() {
    console.log('this is a.js'); 
    b();
}
export default a;

b.js 文件

function b() {
    console.log('this is b.js')
}
export default b;

webpack配置文件(webpack.config.js)

const path = require('path');

module.exports = {
  entry: './app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    chunkFilename: '[name].bundle.js'
  }
};

打包之后的文件

0.bundle.js
main.js

main.js的内容

/******/ (function(modules) { // webpackBootstrap
/******/     // install a JSONP callback for chunk loading
/******/     var parentJsonpFunction = window["webpackJsonp"];
/******/     window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {
/******/         // add "moreModules" to the modules object,
/******/         // then flag all "chunkIds" as loaded and fire callback
/******/         var moduleId, chunkId, i = 0, resolves = [], result;
/******/         for(;i < chunkIds.length; i++) {
/******/             chunkId = chunkIds[i];
/******/             if(installedChunks[chunkId]) {
/******/                 resolves.push(installedChunks[chunkId][0]);
/******/             }
/******/             installedChunks[chunkId] = 0;
/******/         }
/******/         for(moduleId in moreModules) {
/******/             if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/                 modules[moduleId] = moreModules[moduleId];
/******/             }
/******/         }
/******/         if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);
/******/         while(resolves.length) {
/******/             resolves.shift()();
/******/         }
/******/
/******/     };
/******/
/******/     // The module cache
/******/     var installedModules = {};
/******/
/******/     // objects to store loaded and loading chunks
/******/     var installedChunks = {
/******/         1: 0
/******/     };
/******/
/******/     // The require function
/******/     function __webpack_require__(moduleId) {
/******/
/******/         // Check if module is in cache
/******/         if(installedModules[moduleId]) {
/******/             return installedModules[moduleId].exports;
/******/         }
/******/         // Create a new module (and put it into the cache)
/******/         var module = installedModules[moduleId] = {
/******/             i: moduleId,
/******/             l: false,
/******/             exports: {}
/******/         };
/******/
/******/         // Execute the module function
/******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/         // Flag the module as loaded
/******/         module.l = true;
/******/
/******/         // Return the exports of the module
/******/         return module.exports;
/******/     }
/******/
/******/     // This file contains only the entry chunk.
/******/     // The chunk loading function for additional chunks
/******/     __webpack_require__.e = function requireEnsure(chunkId) {
/******/         var installedChunkData = installedChunks[chunkId];
/******/         if(installedChunkData === 0) {
/******/             return new Promise(function(resolve) { resolve(); });
/******/         }
/******/
/******/         // a Promise means "currently loading".
/******/         if(installedChunkData) {
/******/             return installedChunkData[2];
/******/         }
/******/
/******/         // setup Promise in chunk cache
/******/         var promise = new Promise(function(resolve, reject) {
/******/             installedChunkData = installedChunks[chunkId] = [resolve, reject];
/******/         });
/******/         installedChunkData[2] = promise;
/******/
/******/         // start chunk loading
/******/         var head = document.getElementsByTagName('head')[0];
/******/         var script = document.createElement('script');
/******/         script.type = 'text/javascript';
/******/         script.charset = 'utf-8';
/******/         script.async = true;
/******/         script.timeout = 120000;
/******/
/******/         if (__webpack_require__.nc) {
/******/             script.setAttribute("nonce", __webpack_require__.nc);
/******/         }
/******/         script.src = __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".bundle.js";
/******/         var timeout = setTimeout(onScriptComplete, 120000);
/******/         script.onerror = script.onload = onScriptComplete;
/******/         function onScriptComplete() {
/******/             // avoid mem leaks in IE.
/******/             script.onerror = script.onload = null;
/******/             clearTimeout(timeout);
/******/             var chunk = installedChunks[chunkId];
/******/             if(chunk !== 0) {
/******/                 if(chunk) {
/******/                     chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));
/******/                 }
/******/                 installedChunks[chunkId] = undefined;
/******/             }
/******/         };
/******/         head.appendChild(script);
/******/
/******/         return promise;
/******/     };
/******/
/******/     // expose the modules object (__webpack_modules__)
/******/     __webpack_require__.m = modules;
/******/
/******/     // expose the module cache
/******/     __webpack_require__.c = installedModules;
/******/
/******/     // define getter function for harmony exports
/******/     __webpack_require__.d = function(exports, name, getter) {
/******/         if(!__webpack_require__.o(exports, name)) {
/******/             Object.defineProperty(exports, name, {
/******/                 configurable: false,
/******/                 enumerable: true,
/******/                 get: getter
/******/             });
/******/         }
/******/     };
/******/
/******/     // getDefaultExport function for compatibility with non-harmony modules
/******/     __webpack_require__.n = function(module) {
/******/         var getter = module && module.__esModule ?
/******/             function getDefault() { return module['default']; } :
/******/             function getModuleExports() { return module; };
/******/         __webpack_require__.d(getter, 'a', getter);
/******/         return getter;
/******/     };
/******/
/******/     // Object.prototype.hasOwnProperty.call
/******/     __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/     // __webpack_public_path__
/******/     __webpack_require__.p = "";
/******/
/******/     // on error function for async loading
/******/     __webpack_require__.oe = function(err) { console.error(err); throw err; };
/******/
/******/     // Load entry module and return exports
/******/     return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {


__webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, 1)).then(a=>{
    console.log('成功加载a.js文件');
    a();
})

/***/ })
/******/ ]);

0.bundle.js的内容

webpackJsonp([0],[
/* 0 */,
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__b_js__ = __webpack_require__(2);


function a() {
    console.log('this is a.js'); 
    Object(__WEBPACK_IMPORTED_MODULE_0__b_js__["a" /* default */])();
}

/* harmony default export */ __webpack_exports__["default"] = (a);

/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
function b() {
    console.log('this is b.js')
}

/* harmony default export */ __webpack_exports__["a"] = (b);

/***/ })
]);

剖析

先来一句概括的话,webpack模块化其实是通过自执行函数启动,然后通过webpack自定义的exports 和require 来实现的模块化。对于代码分割,webpack自定义了一个函数以jsonp的方式加载js文件。下面开始慢慢详解。

首先我们先看启动文件(也就是第一个运行的js文件,这里是main.js),这个文件会以自执行的方式启动。我这里把无关注释删除,代码折叠之后的截图。
image
其实就是一个自执行函数,长这样的

(function(modules){})([])

然后我们看这个自执行函数干了什么事情?

image

1.定义了一个webpackJsonp的方法挂到了windows对象下面

此方法是一个回调函数,会用在chunk加载完成之后立即执行这个函数的作用有三个

a.加载chunk

首先介绍一下变量installedChunks,这个变量记录了chunk的加载情况,0代表已经加载 , [resolve,reject]代表着正在加载。所以看下面的for循序,是把chunkIds全部记录到installedChunks中,并标记为已经加载

image

b.加载module

image

c.执行传进来的module

如果executeModule存在,则对其中对应moduleId的模块进行运行,我这个打包chul出来的文件里面没有这块代码,估计是因为webpack比较智能。不需要这个功能就把代码省略了吧。

2.定义了__webpack_require__函数

此函数的作用是根据传进来的模块id执行对应模块的代码。__webpack_require__上还挂载了其他一些方法和属性。

__webpack_require__.e
__webpack_require__.m
__webpack_require__.c
__webpack_require__.d
__webpack_require__.n
__webpack_require__.o
__webpack_require__.p
__webpack_require__.oe

image

上边这个函数(__webpack_require__)的作用是执行某一模块,并将其加入到缓存,然后返回模块的exports

image

__webpack_require__.e 函数的作用是如果存在代码分割,那后续的chunk的加载都是使用此函数加载,此函数会创建一个script标签,并从服务器请求相应的js文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值