[英]node.js use modules without assigning them to variables
In node.js, I have to put a stem in front of my module before I can call anything in it:在 node.js 中,我必须在模块前面放置一个词干,然后才能调用其中的任何内容:
const example = require('example.js');
example.func();
I have a really messy node.js file and I would like to break it up into several pieces.我有一个非常混乱的 node.js 文件,我想把它分成几部分。 However, my code looks something like this:
但是,我的代码看起来像这样:
function func1(){ /* ... */ }
function func2(){ /* ... */ }
//blah blah
func1();
//blah blah
func2();
If I split this up into file1.js and file2.js, my code would need to look like this:如果我将其拆分为 file1.js 和 file2.js,我的代码需要如下所示:
var file1 = require('file1.js');
var file2 = require('file2.js');
//blah blah
file1.func1();
//blah blah
file2.func2();
I have to put file1 or file2 before my function to call it, which is something I would like to avoid.我必须在我的 function 之前放置 file1 或 file2 来调用它,这是我想避免的。 Is it possible to not have these stems?
有没有可能没有这些茎?
Clarification I want multiple functions per file.澄清我希望每个文件有多个功能。 The example just uses 1 function per file as an example.
该示例仅使用每个文件 1 个 function 作为示例。
It sounds like you want each export to export just the function, rather than an object containing the function.听起来您希望每个导出仅导出 function,而不是包含 function 的 object。 In
file1
and file2
, do:在
file1
和file2
中,执行:
module.exports = function func1() {
};
instead of代替
module.exports.func1 = function func1() {
};
And then you can call the functions like:然后你可以调用如下函数:
var func1 = require('file1.js');
var func2 = require('file2.js');
//blah blah
func1();
//blah blah
func2();
(it would probably make sense to rename the filenames to func1.js
and func2.js
as well) (将文件名重命名为
func1.js
和func2.js
可能也有意义)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.