webpack in the import, exports realization principle

In fact, the use webpack the script packaged in development, each file will use the import statement to import some of the features, will use the export statement to export some of the features, in order to study the principles of import and export, to study the code of webpack package, principle is very simple:

webpack all input files are packaged into one file:

In the final output file, WebPACK defines an Object object that placed the contents of all of the input file, a file name key, file contents (character string) as the value, such as:

var modules= {};

modules [ 'index'] = "source code";

modules [ 'hello'] = 'source';

 

Of course, the source code will WebPACK certain modifications, will be modified to exports the export statement variable = value of this method, is a parameter exports, probably like this:

 

modules['index'] = (function(exports) {

  // code placed in a private domain.

  // through exports objects, the variable needs disclosed function, class exposes out.

  exports.xx = xxx;

});

This is probably the end result of a source file, into a function, then the exports in the end is what the object? In fact, exports is a Object object, which in fact does not have any content, all content of the function set, serve only to pass an object to import statement:

Let's look at the syntax of import: import xxx from 'filename'

import statement, probably will eventually become so:

var cmp1 = require('filename');

probably require function implementation:

function require(id) {

if(installedModules[id]) {

  return installedModules [id] .exports; // return the object exports

}

var module = installedModules[id] = {
      i: moduleId,
      l: false,
      exports: {} // objects defined exports
 };
 
modules [id] (module.exports); // pass the parameters to the function exports
return module.exports; // finally return
}
 
Regardless of import xxx xxx statement of how to set and eventually will become a variable reference module exports an object, and then access the variables, functions, and so on through this variable:
import { a, b } from 'filename'
 
console.log(a);
console.log(b);
 
The final result of the compilation:
var cmp1 = require('filename');
console.log(cmp1.a);
console.log(cmp1.b);
 
Finally, traditional execution code file entry file require ( 'index');

Guess you like

Origin www.cnblogs.com/kuku/p/11247316.html