在Node.js中,可以使用require
函数来加载模块。默认情况下,当使用require
加载一个模块时,Node.js会首先在当前目录下的node_modules
文件夹中查找该模块。
如果你想要避免加载node_modules
文件夹中的脚本,可以使用以下方法:
使用./
前缀来加载模块,例如require('./mymodule')
。这将会加载当前目录下的mymodule.js
脚本,而不是node_modules
文件夹中的同名模块。
使用绝对路径来加载模块,例如require('/path/to/mymodule')
。这将会加载指定路径下的mymodule.js
脚本,而不是node_modules
文件夹中的同名模块。
下面是一个示例代码,演示如何使用以上方法来加载模块:
// 不加载 node_modules 文件夹中的脚本
const path = require('path');
// 使用相对路径加载模块
const myModule = require('./mymodule');
// 使用绝对路径加载模块
const myModule2 = require(path.resolve('/path/to/mymodule'));
请注意,这种方法只会阻止加载当前目录下的node_modules
文件夹中的脚本,如果你在其他目录下使用require
加载模块,Node.js仍然会搜索node_modules
文件夹。如果你想要完全禁止加载node_modules
文件夹中的模块,可以在启动Node.js应用程序时使用--no-deprecation
参数。例如:node --no-deprecation app.js
。