Node.js require 模塊加載原理 All In One


Node.js require 模塊加載原理 All In One

require 加載模塊,搜索路徑


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

function Module(id, parent) {
  this.id = id;
  this.path = id;
  // path = (id - filename.js)
  this.paths = [];
  // [paths1, parent path, ..., root path]
  // paths1 = (id - filename.js) + node_modules
  this.exports = {};
  this.parent = parent;
  this.filename = null;
  this.loaded = false;
  this.children = [];
}

// ✅ 在原型上添加只有實例才可以訪問的實例方法 require
Module.prototype.require = function(path) {
  // 調用構造函數的靜態方法 Module._load
  return Module._load(path, this);
};

// 用模塊的絕對路徑,那么除了 module.filename
// Node 還提供一個 require.resolve 方法,供外部調用,用於從模塊名取到絕對路徑
require.resolve = function(request) {
  return Module._resolveFilename(request, self);
};

Module.prototype.load = function(filename) {
  var extension = path.extname(filename) || '.js';
  if (!Module._extensions[extension]) {
    extension = '.js';
  }
  Module._extensions[extension](this, filename);
  this.loaded = true;
};

// 首先,將模塊文件讀取成字符串;
// 然后剝離 utf8 編碼特有的 BOM 文件頭,最后編譯該模塊.
Module._extensions['.js'] = function(module, filename) {
  var content = fs.readFileSync(filename, 'utf8');
  module._compile(stripBOM(content), filename);
};

Module._extensions['.json'] = function(module, filename) {
  var content = fs.readFileSync(filename, 'utf8');
  try {
    module.exports = JSON.parse(stripBOM(content));
  } catch (err) {
    err.message = filename + ': ' + err.message;
    throw err;
  }
};

Module.prototype._compile = function(content, filename) {
  var self = this;
  var args = [self.exports, require, self, filename, dirname];
  return compiledWrapper.apply(self.exports, args);
}

// 👍 上面的代碼基本等同於下面的形式
// (function (exports, require, module, __filename, __dirname) {
//   // 模塊源碼
// });

Module._load = function(request, parent, isMain) {
  // 計算絕對路徑
  var filename = Module._resolveFilename(request, parent);
  //  第一步:如果有緩存,取出緩存
  var cachedModule = Module._cache[filename];
  if (cachedModule) {
    return cachedModule.exports;
  }
  // 第二步:是否為內置模塊
  if (NativeModule.exists(filename)) {
    return NativeModule.require(filename);
  }
  // 第三步:生成模塊實例,存入緩存
  var module = new Module(filename, parent);
  // ✅ 實例化 module
  Module._cache[filename] = module;
  // 第四步:加載模塊
  try {
    module.load(filename);
    hadException = false;
  } finally {
    if (hadException) {
      delete Module._cache[filename];
    }
  }
  // 第五步:輸出模塊的exports屬性
  return module.exports;
}

// Module._cache = [];

Module._resolveFilename = function(request, parent) {
  // 第一步:如果是內置模塊,不含路徑返回
  if (NativeModule.exists(request)) {
    return request;
  }
  // 第二步:確定所有可能的路徑
  var resolvedModule = Module._resolveLookupPaths(request, parent);
  var id = resolvedModule[0];
  var paths = resolvedModule[1];
  // 第三步:確定哪一個路徑為真
  var filename = Module._findPath(request, paths);
  if (!filename) {
    var err = new Error("Cannot find module '" + request + "'");
    err.code = 'MODULE_NOT_FOUND';
    throw err;
  }
  return filename;
};

Module._resolveLookupPaths = function(request, parent){
  // 列出可能的路徑
}

// 確認哪一個路徑為真
Module._findPath = function(request, paths) {
  // 列出所有可能的后綴名:.js,.json, .node
  var exists = Object.keys(Module._extensions);
  // 如果是絕對路徑,就不再搜索
  if (request.charAt(0) === '/') {
    paths = [''];
  }
  // 是否有后綴的目錄斜杠
  var trailingSlash = (request.slice(-1) === '/');
  // 第一步:如果當前路徑已在緩存中,就直接返回緩存
  var cacheKey = JSON.stringify({request: request, paths: paths});
  if (Module._pathCache[cacheKey]) {
    return Module._pathCache[cacheKey];
  }
  // 第二步:依次遍歷所有路徑
  for (var i = 0, PL = paths.length; i < PL; i++) {
    var basePath = path.resolve(paths[i], request);
    var filename;

    if (!trailingSlash) {
      // 第三步:是否存在該模塊文件
      filename = tryFile(basePath);
      if (!filename && !trailingSlash) {
        // 第四步:該模塊文件加上后綴名,是否存在
        filename = tryExtensions(basePath, exists);
      }
    }
    // 第五步:目錄中是否存在 package.json
    if (!filename) {
      filename = tryPackage(basePath, exists);
    }
    if (!filename) {
      // 第六步:是否存在目錄名 + index + 后綴名
      filename = tryExtensions(path.resolve(basePath, 'index'), exists);
    }
    // 第七步:將找到的文件路徑存入返回緩存,然后返回
    if (filename) {
      Module._pathCache[cacheKey] = filename;
      return filename;
    }
  }
  // 第八步:沒有找到文件,返回false
  return false;
};


module.exports = Module;

// 模塊的加載實質上
// 注入 exports、require、module 三個全局變量;
// 然后執行模塊的源碼;
// 最后將模塊的 exports 變量的值輸出.


exports = module.exports

✅ module.exports 與 exports 指向同一個Object 引用

https://blog.tableflip.io/the-difference-between-module-exports-and-exports

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

// ✅ module.exports 與 exports 指向同一個Object 引用

// SyntaxError: Identifier 'module' has already been declared
// module = {
//   exports: {},
//   //others
// };
// // {exports: {…}}

// module.exports;
// // {}

// exports = module.exports;
// // {}

// exports.a = `a`;

// module.exports.a = `aa`;
// module.exports.b = `b`;

// log(`exports =`, exports);
// log(`module.exports =`, module.exports);

/*

exports = { a: 'aa', b: 'b' }
module.exports = { a: 'aa', b: 'b' }

*/

const test = () => {
  const module = {
    exports: {},
    //others
  };
  // {exports: {…}}
  module.exports;
  // {}
  const exports = module.exports;
  // {}
  exports.a = `a`;
  module.exports.a = `aa`;
  module.exports.b = `b`;
  log(`exports =`, exports);
  log(`module.exports =`, module.exports);
}
test();

/*

exports = { a: 'aa', b: 'b' }
module.exports = { a: 'aa', b: 'b' }

*/

node_modules

  paths: [
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
    '/Users/xgqfrms-mbp/Documents/node_modules',
    '/Users/xgqfrms-mbp/node_modules',
    '/Users/node_modules',
    '/node_modules'
  ]


➜  module.exports git:(master) ✗ node test.js
exports = {}
module.exports = [Function: app] { test: 'abc' }
module Module {
  id: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/app.js',
  path: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports',
  exports: [Function: app] { test: 'abc' },
  parent: Module {
    id: '.',
    path: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports',
    exports: {},
    parent: null,
    filename: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/test.js',
    loaded: false,
    children: [ [Circular] ],
    paths: [
      '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/node_modules',
      '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
      '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
      '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
      '/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
      '/Users/xgqfrms-mbp/Documents/node_modules',
      '/Users/xgqfrms-mbp/node_modules',
      '/Users/node_modules',
      '/node_modules'
    ]
  },
  filename: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/app.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.exports/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
    '/Users/xgqfrms-mbp/Documents/node_modules',
    '/Users/xgqfrms-mbp/node_modules',
    '/Users/node_modules',
    '/node_modules'
  ]
}

app = [Function: app] { test: 'abc' } undefined
args = []
test = abc

path & paths

function Module(id, parent) {
  this.id = id;
  this.path = path;// id - filename.js
  this.paths = [path, parent path, ..., root path];
  this.exports = {};
  this.parent = parent;
  this.filename = null;
  this.loaded = false;
  this.children = [];
}

module.exports = Module;


var module = new Module(filename, parent);


demo


const log = console.log;

// module.js

log('module.id: ', module.id);
log('module.exports: ', module.exports);
log('module.parent: ', module.parent);
log('module.filename: ', module.filename);
log('module.loaded: ', module.loaded);
log('module.children: ', module.children);
log('module.paths: ', module.paths);

log(`\nmodule =`, module);

/*

$ node module.js

module.id:  .
module.exports:  {}
module.parent:  null
module.filename:  /Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.js
module.loaded:  false
module.children:  []
module.paths:  [
  '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
  '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
  '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
  '/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
  '/Users/xgqfrms-mbp/Documents/node_modules',
  '/Users/xgqfrms-mbp/node_modules',
  '/Users/node_modules',
  '/node_modules'
]

*/


/*

module = Module {
  id: '.',
  path: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system',
  exports: {},
  parent: null,
  filename: '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/module.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/module-system/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/src/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/learn-node.js-by-practice/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
    '/Users/xgqfrms-mbp/Documents/node_modules',
    '/Users/xgqfrms-mbp/node_modules',
    '/Users/node_modules',
    '/node_modules'
  ]
}

*/

CommonJS

https://en.wikipedia.org/wiki/CommonJS

require() function & module.exports (alias, exports)


default exports

module.exports = xxx;

module.exports.xxx = xxx;
module.exports = {
  xxx: xxx,
};

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

const app = (datas = [], debug = false) => {
  log(`datas =`, datas)
};

// 👎❌
// exports = app;

// ✅ module export (const { app, } = require(`./app`);)
// exports.app = app;

// 👍✅ default export (const app = require(`./app`);)
module.exports = app;

// ✅
// module.exports.app = app;

// ✅
// module.exports = {
//   app,
// };



module.exports 覆蓋 exports

const log = console.log;

log(`exports`, exports);
log(`module`, module);

// TypeError: Cannot set property 'a' of undefined
// module.export.a = 1;
// module.export.b = 2;
// module.export.c = 3;
// module.export.d = 4;

// 自定義屬性 umd ✅
module.umd = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
};
// 自定義屬性 export ✅
module.export = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
};

exports.a = 11;
exports.b = 22;
exports.c = 33;
exports.d = 44;

// module.exports 覆蓋 exports
module.exports = { c: 333 };
module.exports.d = 444;

log(`\nexports`, exports);
log(`module`, module);


/*


exports { a: 11, b: 22, c: 33, d: 44 }
module Module {
  id: '.',
  path: '/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/src',
  exports: { c: 333, d: 444 },
  parent: null,
  filename: '/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/src/export.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/src/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/umd-npm-package/node_modules',
    '/Users/xgqfrms-mbp/Documents/GitHub/node_modules',
    '/Users/xgqfrms-mbp/Documents/node_modules',
    '/Users/xgqfrms-mbp/node_modules',
    '/Users/node_modules',
    '/node_modules'
  ],
  umd: { a: 1, b: 2, c: 3, d: 4 },
  export: { a: 1, b: 2, c: 3, d: 4 }
}
*/

https://nodejs.org/api/modules.html#modules_exports_shortcut

refs

http://www.ruanyifeng.com/blog/2015/05/require.html

Module System

https://www.cnblogs.com/xgqfrms/p/9493550.html

node --experimental-modules & node.js ES Modules

https://www.cnblogs.com/xgqfrms/p/13591967.html



©xgqfrms 2012-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM