我应该把包依赖传递给模块函数,还是只在模块文件中需要它们?

Should I pass package dependencies to a module function or just require them in the module file?

本文关键字:模块 文件 函数 包依赖 依赖 我应该      更新时间:2023-09-26

我理解可以通过将模块导出为带有您希望传递的每个变量的参数的函数来将变量传递给模块。例如

module.exports = module.exports = function (injectedVariable) {
  app.get('/whatever', function (req, res, next) {
     // Do something with injectedVariable
  });
};

我理解这对于在不同模块周围传递像"app"这样的变量是有用的。但是,处理外部包依赖关系的首选模式是什么?我曾见过这样的代码。

App.js

var jquery = require('jquery');
var _ = require('underscore');
var backbone = require('backbone');
var express = require('express');
// Pretty much every other external library
var app = express();
// Code here might config some of the 3rd party modules
require('routes/main.js')(app, _, jquery, backbone, someOtherModule, someOtherModule2);
require('routes/main.js')(app, _, jquery, backbone, someOtherModule, someOtherModule2);
// Etc
// Init server etc

然后每个路由模块将导出一个函数,其中包含所有可用的参数,以支持需要传递给它们的包。

这样做有什么原因吗?在每个文件的顶部只要求('whatever')不是更干净吗?据推测,在不同的文件中对同一个模块使用许多require()并不是问题,因为node将从运行时遇到的require()的第一个实例中提取其缓存版本。哪种管理包依赖关系的方法是首选的?

这样做有什么原因吗?

对于像underscore、jquery、backbone这样的常规模块使用这种模式,明显违反了构建node的基本CommonJS模式。不要这样做。只需要你的模块直接使用CommonJS语法。对于测试和依赖注入,有一些commonjs兼容的方法可以实现,比如rewire或injector。

但是,它与express app实例不同,因为它是具有特定配置的特定对象,因此可以传入它。但是,express 4消除了使用此模式的最常见需求,因为您可以在外部主应用程序中挂载子应用程序。