[英]node.js use modules without assigning them to variables
在 node.js 中,我必須在模塊前面放置一個詞干,然后才能調用其中的任何內容:
const example = require('example.js');
example.func();
我有一個非常混亂的 node.js 文件,我想把它分成幾部分。 但是,我的代碼看起來像這樣:
function func1(){ /* ... */ }
function func2(){ /* ... */ }
//blah blah
func1();
//blah blah
func2();
如果我將其拆分為 file1.js 和 file2.js,我的代碼需要如下所示:
var file1 = require('file1.js');
var file2 = require('file2.js');
//blah blah
file1.func1();
//blah blah
file2.func2();
我必須在我的 function 之前放置 file1 或 file2 來調用它,這是我想避免的。 有沒有可能沒有這些莖?
澄清我希望每個文件有多個功能。 該示例僅使用每個文件 1 個 function 作為示例。
聽起來您希望每個導出僅導出 function,而不是包含 function 的 object。 在file1
和file2
中,執行:
module.exports = function func1() {
};
代替
module.exports.func1 = function func1() {
};
然后你可以調用如下函數:
var func1 = require('file1.js');
var func2 = require('file2.js');
//blah blah
func1();
//blah blah
func2();
(將文件名重命名為func1.js
和func2.js
可能也有意義)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.