首页 > 解决方案 > 向下传递模块 - javascript

问题描述

我有这样的结构:

-controllers
 -matches
  -index.js
  -create.js
  -get.js

在索引中,我像这样导出其他模块:

const get = require("./get");
const create = require("./create");

module.exports = {
  get,
  create,
}

获取示例:

const MatchModel = require("../../models/Match");

const get = async (req, res, next) => {
  let matches = await MatchModel.find();
  console.log(matches);
};

module.exports = get;

现在既然 get 和 create 共享同一个模块(MatchModel),有没有办法将它传递下来,而不是在每个文件中都导入它?

我想做的是这样的:索引:

const MatchModel = require("../../models/Match");
const get = require("./get");
const create = require("./create");

module.exports = {
  get,
  create,
}

获取示例:

const get = async (req, res, next) => {
  let matches = await MatchModel.find();
  console.log(matches);
};

module.exports = get;

我正在使用猫鼬作为架构。

标签: javascriptnode.jsmongodbimport

解决方案


在您的 index.js 或 app.js 中,导出快速应用程序的脚本文件添加

global_get = require("../get"); // with the path according to your structure

没有标识符

标识符,如constletvar

现在您基本上可以在您的 nodejs 应用程序中的任何位置调用此模块/函数,例如:

let result = await global.global_get();

如果您有一系列导出功能,则:

let result = await global.global_get.some_function();

在这里,globalGLOBAL (depreciated) 标识整个 nodejs 应用程序中的全局变量。

但是,我建议您在需要的地方导入/需要模块


推荐阅读