Preface:

Before using ES6 to write code,webpack after the online, no problem, I have seen the packaged code, long very messy, I did not dare to see what happened, after loading it will run!

Today, we will use an example to understand the code before and after packaging!

  1. Create a folder and create two folders inside,app folder and public folder. App folder is used to store the raw data and JavaScript modules we will write, and public folder is used to store files for the browser to read later (including js files generated using webpack and oneindex.htmlFile). Next we create three more files:
  • index.htmlPut it in the public folder.
  • Greeter.js— Put it in app folder;
  • main.js— Put it in app folder;

The project structure is shown in the figure below






The project structure

We write the basic HTML code in the index.html file, which is used to import the packaged JS file (we’ll name the packaged JS file bundle.js, which we’ll cover in more detail later).

<! -- index.html -->

        
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>sample Project</title>
  </head>
  <body>
    <div id='root'>
    </div>
    <script src="bundle.js"></script>
  </body>
</html>
Copy the code

We define a function in greeter.js that returns an HTML element containing a greeting and export the function as a module according to the CommonJS specification: greeter.js

// Greeter.js
exports.greet= function() {
  var greet = document.createElement('div');
  greet.textContent = "Hi there and greetings!";
  return greet;
};

exports.USER_INFO = "userInfo";
Copy the code

In the main.js file, we write the following code to insert a node returned by the Greeter module into the page.

//main.js 
 let {greeter,USER_INFO} =require('./Greeter.js');
console.log(USER_INFO);
document.querySelector("#root").appendChild(greeter());Copy the code

After using Webpack:

(function(modules){//===== method body =========//
    var installedModules = {};// Cache loaded modules
   function  __webpack_require__(moduleId) {
        if (installedModules[moduleId]) {
            return installedModules[moduleId].exports;
        }
        var module = installedModules[moduleId] = {
            i: moduleId,
            l: false,
            exports: {}
        };
        modules[moduleId].call(module.exports, module.module.exports, __webpack_require__);
        module.l = true;
        return module.exports;
    }
    __webpack_require__.m = modules;
    __webpack_require__.c = installedModules;
    __webpack_require__.d = function(exports, name, getter) {
        if(! __webpack_require__.o(exports, name)) {Object.defineProperty(exports, name, {
                configurable: false, 
                enumerable: true.get: getter }); }}; __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;
    };
    __webpack_require__.o = function(object, property) {
        return Object.prototype.hasOwnProperty.call(object, property);
    };
    __webpack_require__.p = "";
    return __webpack_require__(__webpack_require__.s = 0); }) (//============ Method parameters ========//
// This is a method parameter to a self-executing function. The parameter is a number containing the main.js module, greeter.js module[(function(module, exports, __webpack_require__) {
    // Here is the main.js module
    let {
        greeter,
        USER_INFO
    } = __webpack_require__(1);
    console.log(USER_INFO);
    document.querySelector("#root").appendChild(greeter()); }),function(module, exports) {
    // // here is the greeter.js module
    exports.greet = function() {
        var greet = document.createElement('div');
        greet.textContent = "Hi there and greetings!";
        return greet;
    };
    exports.USER_INFO = "userInfo"; })]);Copy the code

Function (module, exports, __webpack_require__) {// Module contents}); function(module, exports, __webpack_require__) {// module contents};

The function is defined at execution time

var installedModules = {}; // Cache loaded module, when imported directlyCopy the code

definefunction __webpack_require__(){} mount static properties and methods __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d =function(exports, name, getter) {
        //...  
    };

    __webpack_require__.n = function(module) {
        //...
   };

    __webpack_require__.o = function(object, property) {
        //...
    };

    __webpack_require__.p = "";

Copy the code

Then execute:

return __webpack_require__(__webpack_require__.s = 0);Copy the code

  • First check that the cache installedModules is not created
var module = installedModules[moduleId] = {
            i: moduleId,
            l: false,
            exports: {}
        };
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);Copy the code

  • Execute modules [0]. Call (…). That is, execute the main.js module passed in

    (function(Module, exports, __webpack_require__) {// here is the main.js modulelet {
            greeter,
            USER_INFO
        } = __webpack_require__(1);
        console.log(USER_INFO);
        document.querySelector("#root").appendChild(greeter());
    })Copy the code

  • Get __webpack_require__(1) at execution time, that is, execute the passed greeter.js module
var module = installedModules[moduleId] = {
            i: moduleId,
            l: false,
            exports: {}
        };
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); Copy the code
  • After executing the Greeter module,return
    exports={
        greet:function() {
            var greet = document.createElement('div');
            greet.textContent = "Hi there and greetings!";
            return greet;
        },
       USER_INFO:"userInfo"
    }Copy the code

So let’s change require to import and see what happens when you package it

We changed the greeter.js message to the following:

// Greeter.js
export default function() {
  var greet = document.createElement('div');
  greet.textContent = "Hi there and greetings!";
  return greet;
};

export const USER_INFO = "userInfo";
Copy the code

The code in main.js file, after modification

//main.js 
import greet,{USER_INFO} from './Greeter.js';
console.log(USER_INFO);
document.querySelector("#root").appendChild(greet());Copy the code

Then we pack again:

(function(modules) {
   var installedModules = {};
   function __webpack_require__(moduleId) {
       if (installedModules[moduleId]) {
           return installedModules[moduleId].exports;
       }
       var module = installedModules[moduleId] = {
           i: moduleId,
           l: false,
           exports: {}
       };
       modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
       module.l = true;
       return module.exports;
   }
   __webpack_require__.m = modules;
   __webpack_require__.c = installedModules;
   __webpack_require__.d = function(exports, name, getter) {
       if(! __webpack_require__.o(exports, name)) { Object.defineProperty(exports, name, { configurable:false,
               enumerable: true, get: getter }); }}; __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;
   };

   __webpack_require__.o = function(object, property) {
       return Object.prototype.hasOwnProperty.call(object, property);
   };

   __webpack_require__.p = "";
  return__webpack_require__(__webpack_require__.s = 0); }) ([(function(module, __webpack_exports__, __webpack_require__) {
   "use strict";
   Object.defineProperty(__webpack_exports__, "__esModule", {
       value: true
   });
   var __WEBPACK_IMPORTED_MODULE_0__Greeter_js__ = __webpack_require__(1);
   //main.js
   console.log(__WEBPACK_IMPORTED_MODULE_0__Greeter_js__["a"]);
   document.querySelector("#root").appendChild(Object(__WEBPACK_IMPORTED_MODULE_0__Greeter_js__["b") ()); }),function(module, __webpack_exports__, __webpack_require__) {

   "use strict";
   __webpack_exports__["b"] = (function() {
       var greet = document.createElement('div');
       greet.textContent = "Hi there and greetings!";
       return greet;
   });;

   const USER_INFO = "userInfo";
   __webpack_exports__["a"] = USER_INFO; })]);Copy the code

__webpack_require__(__webpack_require__ = 0)

To execute the main.js module:

function(module, __webpack_exports__, __webpack_require__) {
   "use strict";
   Object.defineProperty(__webpack_exports__, "__esModule", {
       value: true
   });
   var __WEBPACK_IMPORTED_MODULE_0__Greeter_js__ = __webpack_require__(1);
   //main.js
   console.log(__WEBPACK_IMPORTED_MODULE_0__Greeter_js__["a"]);
   document.querySelector("#root").appendChild(Object(__WEBPACK_IMPORTED_MODULE_0__Greeter_js__["b") ()); }Copy the code

The difference between:

Different from require, the new __esModule attribute indicates that it is a module defined by JS export, and the introduction method is also different

Require imports the entire module.exports object, and each time imports the whole object, defines variables to get the properties inside

Import directly fetches the __WEBPACK_IMPORTED_MODULE_0__Greeter_js__[” A “] attribute value

Similarities:

Before compilation: are didn’t give the head and tail packing module first, scope isolated, by passing in the module, the module. The exports, the require as a parameter called module, and the cache module

(function(module, __webpack_exports__ __webpack_require__) {/ / module code})Copy the code