[Excerpt] The module loading mechanism

The module loading mechanism

CommonJS module loading mechanism that is a copy of the input value is outputted, a value that is once output, the impact of changes within a module is less than this value.

Here is a module file lib.js

// lib.js
var counter = 3;
function incCounter(){
    counter ++;
}
module.exports = {
    counter,
    incCounter
}

The above code output internal variables counterand internal methods of this variable is rewritten incCounter.

Then loads the module above.

// main.js
var counter = require('./lib').counter;
var incCounter = require('./lib').incCounter;

console.log(counter) //3
incCounter();
console.log(counter) //3

Codes described above, counterafter the output module changes within lib.js not affecting counterthe

# 5.1 require internal processing flow

requireAmong CommonJS command is used to load another module specification command.

  • In fact, he is not a global command, but points to the current module module.requirecommand, which in turn calls the internal command Node, and Module._load.
Module._load = function(request, parent, isMain) {
  // 1. 检查 Module._cache,是否缓存之中有指定模块
  // 2. 如果缓存之中没有,就创建一个新的Module实例
  // 3. 将它保存到缓存
  // 4. 使用 module.load() 加载指定的模块文件,
  //    读取文件内容之后,使用 module.compile() 执行文件代码
  // 5. 如果加载/解析过程报错,就从缓存删除该模块
  // 6. 返回该模块的 module.exports
};

The above step 4, using module.compile()the script for performing the specified module, logic is as follows.

Module.prototype._compile = function(content, filename) {
  // 1. 生成一个require函数,指向module.require
  // 2. 加载其他辅助方法到require
  // 3. 将文件内容放到一个函数之中,该函数可调用 require
  // 4. 执行该函数
};

The above steps 1 and Step 2, requirethe function as primary and secondary methods.

  • require(): Loading external modules
  • require.resolve(): The module name resolved to an absolute path
  • require.main: Pointing to the main module
  • require.cache: All point to the cache module
  • require.extensions: According to the file extension, call different functions to perform

Once the requirefunction is ready, the entire contents of the script to be loaded, it was placed into a new function, to avoid polluting the global environment. The function parameters include require, , module, exportsand other parameters.

(function (exports, require, module, __filename, __dirname) {
  // YOUR CODE INJECTED HERE!
});

Module._compileThe method is performed synchronously, so Module._loadto wait for it to complete execution, will return to the user module.exportsvalue.

【end】

Guess you like

Origin www.cnblogs.com/wuxiaoyi/p/11937289.html