【问题标题】:node.js use modules without assigning them to variablesnode.js 使用模块而不将它们分配给变量
【发布时间】:2019-10-09 04:06:08
【问题描述】:

在 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();

我必须将 file1 或 file2 放在我的函数之前才能调用它,这是我想避免的。有没有可能没有这些茎?

澄清 我想要每个文件有多个功能。该示例仅使用每个文件 1 个函数作为示例。

【问题讨论】:

  • 好吧,你可以在 file1.js 中使用 global.func1 = function() { /* ... */ } 之类的代码 - 但是在模块中使用 global 很容易出现各种问题
  • 你可以做到require('file1.js').func1() - 这是你的意思吗?
  • @pguardiario 不,我只想写 func1

标签: javascript node.js import


【解决方案1】:

听起来您希望每个导出都只导出函数,而不是包含函数的对象。在file1file2 中,执行:

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.jsfunc2.js

【讨论】:

  • 很抱歉没有放这个,但我希望每个文件有 1 个以上的功能。这个解决方案仍然非常有用,因为我现在至少可以拆分我的代码了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2017-12-27
  • 1970-01-01
相关资源
最近更新 更多