As mentioned in the previous step, I don’t agree with the webpack leader, so I have to…

Here in
Programmer grey(PS: I also don’t know if the link is original)

Awkward interview questions

Q: what are the JS modular solutions you know of? A: Js modular generally has Commonjs AMD(CMD) ESModule, Commonjs synchronous loading is generally used for Node, AMD(CMD) because it is asynchronous loading is generally used in the front end. ESModule aims to unify the front and back end modularity. It’s scary in its simplicity. Excellent…

Q: So why synchronous Commonjs on Node and asynchronous AMD on the front end? A: The Node application runs on the server, and the program can read the files of each module directly through the file system. It is characterized by fast response and will not block the operation of the program because of synchronization. The front-end project runs in the browser, where each module loads JS files via HTTP requests, and is subject to network and other factors that can cause the browser to “freeze” – that is, get stuck. Affect user experience. The whole encounter has been completely covered.

Q: Have you heard of Webpack? Know how WebPack is modularized? A: WebPack is designed to convert ES6 modular code into Commonjs to be browser-compatible. Inconsistent, starting to get a little twitchy, but holding back the hope of muddling through…

Q: Ok, since you say that Commonjs synchronization doesn’t work in the front end, why should the Commonjs form of webPack transcode run in the front end? A: emmmmm

Interviewer: How about today’s interview stop here, you go back to wait for the announcement… I: HMMMMM

What exactly does Webpack do

Execute the webpack command over and over again, and study the generated bundle.js over and over again. Uh huh? All js modules are packed into a bundle.js file, which is not loaded by modules, whether synchronous or asynchronous. Js files are loaded directly into memory, which is much easier than nodeJS files.

So how does WebPack assemble so many files into a bundle.js file? Carefully think about it, or the book and everyone together to learn it, or feel this series of articles will become emoticons to share tutorials! The 2019-01-25-16-16-47

Next, I will share the Commonjs and ES6 Module modules for webpack processing. If you have any questions about these two modules, please Google them. In fact, the so-called modularity is nothing more than adding two keys to a piece of code to realize communication with other codes, calling each other, obtaining the ability to introduce other modules through require, and realizing the function of outputting methods to other modules through export.

Commonjs modular processing

First add an NPM script to modify package.json as shown below:

/node_modules/.bin/webpack can be discarded and only NPM run build is required.

Build the project code, code address, where the contents of index.js:

const foo = require('./foo');

console.log(foo);
console.log('I'm a senior front End engineer.');
Copy the code

Foo. Js content:

module.exports = {
  name: 'quanquan'.job: 'fe'};Copy the code

After executing the NPM run build, let’s look at the bundle.js package.

(function(modules) {
	// Cache module objects
	var installedModules = {};
	// Simulate the commonJS implementation of require
	function __webpack_require__(moduleId) {
		// require modules that are already cached
		if(installedModules[moduleId]) {
			return installedModules[moduleId].exports;
		}
		// create a module and store a reference to the new module in the cache
		var module = installedModules[moduleId] = {
            / / module id
            i: moduleId,
            // Whether the module is loaded
            l: false.// The body of the module will be overwritten
			exports: {}
		};
		// Execute the following module wrapper function and place this inside the module as the module body
		modules[moduleId].call(module.exports, module.module.exports, __webpack_require__);
		// Mark the module as loaded
		module.l = true;
		// Return the module body
		return module.exports;
	}
    // Expose all modules outwards
	__webpack_require__.m = modules;
	// Expose cached modules outwards
    __webpack_require__.c = installedModules;

    // The following two methods are not used yet
	// 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. The prototype. The hasOwnProperty. Call this is no good explanation
    // Js authoritative guide says
    __webpack_require__.o = function(object, property) {
        return Object.prototype.hasOwnProperty.call(object, property);
    };

    // __webpack_public_path__
    // We haven't used this yet
	__webpack_require__.p = "";
    // Load entry module and return exports
    // When the preparation is done, require the entry module to make the project run
	return __webpack_require__(__webpack_require__.s = 0);
})
/ * * * * * * * * gorgeous line above the webpack initialization code, here are we write the module code of * * * * * * * * * * * * * * * /
([
/* Module 0 corresponds to index.js */
/ * * * / (function(module, exports, __webpack_require__) {

const foo = __webpack_require__(1);

console.log(foo);
console.log('I'm a senior front End engineer.');


/ * * * / }),
/* Module 1 corresponds to foo.js */
/ * * * / (function(module, exports) {

module.exports = {
  name: 'quanquan'.job: 'fe'};/ * * * /})]);Copy the code

The original webpack is the code we wrote with a wrapper function wrapped up, and then execute __webpack_require__ to call the wrapper function. Through the code inside the wrapper function, we rewrote the exports attribute of the parameter module and got the main code of the module we wrote.

So we see the code wrapped in index.js as follows:

function(module, exports, __webpack_require__) {
    const foo = __webpack_require__(1);
    console.log(foo);
    console.log('I'm a senior front End engineer.');
}
Copy the code

The wrapped code for foo.js is:

function(module, exports) {
    module.exports = {
        name: 'quanquan'.job: 'fe'}; }Copy the code

Since index.js has require(‘./foo’), __webpack_require__ is added to the wrapper function argument generated by index.js to import the foo module. Of course, this piece of content requires you to think a little bit. We also hope that you can put your thoughts and questions in the comments section, and we can discuss together.

Es6 Module Module processing

To change our project code to ES6 modular code, first modify index.js:

import foo from './foo';

console.log(foo);
console.log('I'm a senior front End engineer.');
Copy the code

Next, modify foo.js

export default {
  name: 'quanquan'.job: 'fe'};Copy the code

Finally, the command line executes NPM run build to pack. Once packaged, bundle.js will look like this (optimized):

(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__foo__ = __webpack_require__(1);
    console.log(__WEBPACK_IMPORTED_MODULE_0__foo__["a"]);
    console.log('I'm a senior front End engineer.');
  },
  function(module, __webpack_exports__, __webpack_require__) {
  	"use strict";
    __webpack_exports__["a"] = ({
      name: 'quanquan'.job: 'fe'}); }]);Copy the code

The result of the package is still gobbledegk code, which is very much the same as commonJS modularization.

The package code generated by index.js is:

function(module, __webpack_exports__, __webpack_require__) {
	"use strict";
	Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
	var __WEBPACK_IMPORTED_MODULE_0__foo__ = __webpack_require__(1);
	console.log(__WEBPACK_IMPORTED_MODULE_0__foo__["a"]);
	console.log('I'm a senior front End engineer.');
}
Copy the code

The package code generated by foo.js is:

function(module, __webpack_exports__, __webpack_require__) {
	"use strict";
	__webpack_exports__["a"] = ({
		name: 'quanquan'.job: 'fe'}); }Copy the code

It is not hard to find the difference with CommonJS:

  • First, wrap the arguments before the functionmodule.exportsTurned out to be__webpack_exports__
  • Second, where the ES6 module import syntax is used, the__webpack_exports__Add attributes__esModule
  • The rest is similar to CommonJS

The __webpack_require__. N method is still not used in commonJS. Can’t you make an issue of Webpack, participating in open source projects is no longer a blank? A fun…

Wouldn’t it be too easy to jump on the bandwagon of international open source projects?

Es6 Module CommonJs

Modify foo.js as follows:

module.exports = {
  name: 'quanquan'.job: 'fe'};Copy the code

The result of packaging is:

/ * * * * * * / (function(modules) { // webpackBootstrap
/ * * * * * * / 	// The module cache
/ * * * * * * / 	var installedModules = {};
/ * * * * * * /
/ * * * * * * / 	// 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;
/ * * * * * * / 	}
/ * * * * * * /
/ * * * * * * /
/ * * * * * * / 	// 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 = "";
/ * * * * * * /
/ * * * * * * / 	// Load entry module and return exports
/ * * * * * * / 	return __webpack_require__(__webpack_require__.s = 0);
/ * * * * * * / })
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
/ * * * * * * / ([
/* 0 */
/ * * * / (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foo__ = __webpack_require__(1);
// __webpack_require__.n is used
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foo___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foo__);


console.log(__WEBPACK_IMPORTED_MODULE_0__foo___default.a);
console.log('I'm a senior front End engineer.');
/* harmony default export */ __webpack_exports__["default"] = ({});


/ * * * / }),
/ * 1 * /
/ * * * / (function(module, exports) {

module.exports = {
  name: 'quanquan'.job: 'fe'};/ * * * / })
/ * * * * * * / ]);
Copy the code

Index.js does not change, which means that when the exported module exports commonJS and the imported module imports es6, the imported module uses __webpack_require__.n.

Webpack packs all modules into a bundle.js file to load modules synchronously, which is really smart. However, if your project is large and involves hundreds or thousands of JS modules, how can you split the code using WebPack? Let’s discuss it together next.