javascript - node.js 使用模块而不将它们分配给变量
问题描述
在 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
和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
)
推荐阅读
- javascript - 为什么我的筛子在寻找素数方面表现不佳?
- arrays - 有没有办法从我的 Google 脚本中排除包含公式的单元格?
- php - 获取标签 [img][/img] php 中的值
- javascript - 使用 webdriver.io 拖放
- javascript - progressbar.js 在 Internet Explorer 11 上不起作用
- node.js - 找不到模块 ../models/category
- git - 无法将更改推送到管理员创建的分支
- php - Firebase PHP API - 如何避免在每个请求中创建 Factory()
- ruby - 如何在 AWS Lambda 处理程序中引发错误
- java - Android CalendarView 无法在高度更改后选择日期