亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將導入函數添加到導出函數中時出現問題

將導入函數添加到導出函數中時出現問題

精慕HU 2023-07-20 16:09:05
所以基本上我想要這個塊:const {someFunction} = require("/somePath");exports.exportedFunction = (req, res) => { someFunction() }像這個塊一樣工作:exports.exportedFunction = (req, res) => {    const {someFunction} = require("/somePath");    someFunction();}但無需重復導入。如何防止每次導出時重復導入?我想要一個導入,我可以在每個導出中使用該函數,而無需完全導入到導出中。這可能嗎?更新:好的,有一個小更新。我已經做了一個最低要求的問題重現,它看起來像這樣://index.jsconst express = require("express");const app = express();const router = require("./router");exports.exportableStuff = () => {    return [1,2,3];};app.use("/", router);app.listen(3000, () => {    console.log("i am listening");});//router.jsconst express = require("express");const router = express.Router();const controller = require("./controller");router.get("/", controller.testModule);module.exports = router;//controller.jsconst {exportableStuff} = require("./index");exports.testModule = (req, res) => {    console.log("it has been done");    exportableStuff();    res.send("<h1>hello, user</h1>");}UPDATE2:我實際上自己設法修復了關閉問題。為了使這項工作有效,我實際上所做的是改變這一點:const {exportableStuff} = require("./index");進入:const model = require("./index");并使用 model.exportableStuff() 調用我的控制器中的函數。問題已正式解決,但如果您有更好的主意,我洗耳恭聽。
查看完整描述

1 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

根據您的評論,我認為您可能想做以下事情?


// index.js

module.exports = { someFunction }

// router.js


// case1

const { someFunction } = require("./index.js")

someFunction() // it will work


// case2

const index = require("./index.js")

index.someFunction() // it will work

但是,如果您想將 someFunction 導出到另一個導出

然后使用新函數,您需要這樣做。


// another.js

const { someFunction } = require("./index.js")

exports.exportedFunction = someFunction

// router.js

const { exportedFunction } = require("./another.js")

exportedFunction() // it will work


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號