为了账号安全,请及时绑定邮箱和手机立即绑定

webpack打包后的代码理解(多个打包入口)

标签:
前端工具

假设webpack.config.js下的入口配置如下:

var  path=require("path");
module.exports={
    entry:{main:"./src/script/main.js",a:"./src/script/a.js"},
    output:{
        path:path.resolve(__dirname ,"dist/js"),
        filename:"[name].js"
    },

}

这里面有两个入口文件,如果main.js和a.js里面并没有共同依赖某个文件,那么打包后分别创建两个打包后的文件。一个main.js,一个a.js.
本文想说的是如果main.js 和a.js里面有共同依赖某个文件时 的代码理解。如:
a.js

require("./b");
console.log("a");

main.js

require("./b");
console.log("helloworld");

b.js

console.log("b");

这种情况下 如果按照最开始的代码直接打包 会出现冗余。为了解决这个问题,要引入一个插件,代码如下:

var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
var  path=require("path");
module.exports={
    entry:{main:"./src/script/main.js",a:"./src/script/a.js"},
    output:{
        path:path.resolve(__dirname ,"dist/js"),
        filename:"[name].js"
    },
    plugins:[
    new CommonsChunkPlugin({name:"common"})

    ]

}

引入这个插件打包后 生成三个文件 一个是a.js 一个main.js 一个conmmon.js
common.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()();
/******/        }
/******/        if(executeModules) {
/******/            for(i=0; i < executeModules.length; i++) {
/******/                result = __webpack_require__(__webpack_require__.s = executeModules[i]);
/******/            }
/******/        }
/******/        return result;
/******/    };
/******/
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // objects to store loaded and loading chunks
/******/    var installedChunks = {
/******/        2: 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) {
/******/        if(installedChunks[chunkId] === 0) {
/******/            return Promise.resolve();
/******/        }
/******/
/******/        // a Promise means "currently loading".
/******/        if(installedChunks[chunkId]) {
/******/            return installedChunks[chunkId][2];
/******/        }
/******/
/******/        // setup Promise in chunk cache
/******/        var promise = new Promise(function(resolve, reject) {
/******/            installedChunks[chunkId] = [resolve, reject];
/******/        });
/******/        installedChunks[chunkId][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 + ".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;
/******/
/******/    // identity function for calling harmony imports with the correct context
/******/    __webpack_require__.i = function(value) { return value; };
/******/
/******/    // 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; };
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

    console.log("b");

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

这是一个立即执行的匿名函数,参数就是打包后的b模块,(ps:它的模块ID被分配为0.)。这个匿名函数 将b模块保存在变量modules数组中,定义了一个全局函数webpackJsonp 和局部函数__webpack_require__。
a.js打包后的代码:

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

__webpack_require__(0);

    console.log("a");

/***/ })
],[1]);

这个模块就是调用webpackJsonp函数,传了三个参数。webpackJSON
这个函数在这里做了几件事,一个是把a模块也保存在modules这个数组中。(ps:它在数组中的下标就是a模块ID),一个是调用webpack_require(1);1是模块a的id,这个函数可以理解成调用a模块,a模块的代码分两个部分,一个执行a模块所依赖的模块:即webpack_require(这里是a模块所依赖的模块的ID),一个是执行a.js。
可以看出webpack_require(这里是a模块所依赖的模块的ID)这个函数又分成连个部分,就这样层层向下网状调用webpack_require这个函数。从而将模块组合在一起。
main.js也是类似。

点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消