module.require是如何使用的?
发布于 6 年前 作者 athrunsun 2199 次浏览 来自 问答

一个使用的例子:https://sourcegraph.com/github.com/nuysoft/Mock/-/blob/src/mock/random/image.js#L252

但是执行的时候会报错:module.require is not a function,相关issue:https://github.com/nuysoft/Mock/issues/222

官方文档里面确实有这个方法(8和10的文档里都有),https://nodejs.org/dist/latest-v8.x/docs/api/modules.html#modules_module_require_id,但是它的使用说明我没看明白:

Note: In order to do this, it is necessary to get a reference to the module object. Since require() returns the module.exports, and the module is typically only available within a specific module’s code, it must be explicitly exported in order to be used.

有人使用过这个方法吗?如何使用呢?它和require()到底有何区别?

2 回复

require函数是module.require的简单封装,require不仅提供了函数本身,还封装了一些如require.resolve、require.paths、require.extensions的便捷方法,这些当然都是调用module的方法,比方说require.extensions === module.constructor._extensions。

FireShot Capture 043 - (15 封私信 _ 80 条消息)module.require和r_ - https___www.zhihu.com_question_291724309.png

@lovelifeloveyou 我这么说你看对不对:

  1. module这个global variable上并没有require这个方法
  2. 把当前模块作为输出的变量export之后,在其它模块里可以引入,而且fooModule.require(path)中的path是相对于fooModule计算而不是引入fooModule的模块
回到顶部