use*_*486 12 javascript import header node.js
这是对Node.js的后续问题,如何从其他文件中"包含"函数?
我想包含一个外部js文件,其中包含node.js应用程序的常用功能.
从In Node.js中的一个答案,如何从其他文件中"包含"函数?,这可以通过
// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
Run Code Online (Sandbox Code Playgroud)
导出每个功能都不方便.是否可以使用单行程输出所有功能?看起来像这样的东西;
module.exports = 'all functions';
Run Code Online (Sandbox Code Playgroud)
这种方式更方便.如果忘记稍后导出某些功能,它也会减少错误.
如果不是单行,是否有更简单的替代方案,使编码更方便?我只想方便地包含一个由常用函数组成的外部js文件.像include <stdio.h>C/C++中的东西.
Tim*_*vic 28
您可以先编写所有函数声明,然后将它们导出到对象中:
function bar() {
//bar
}
function foo() {
//foo
}
module.exports = {
foo: foo,
bar: bar
};
Run Code Online (Sandbox Code Playgroud)
虽然没有神奇的单行,但您需要明确导出您想要公开的功能.
Joe*_*rne 14
一个非常老的问题,但我只需要自己解决同样的问题。我使用的解决方案是在模块内定义一个 Class 来包含我的所有函数,并简单地导出该类的一个实例。
classes.js 看起来像这样:
class TestClass
{
Function1() {
return "Function1";
}
Function2() {
return "Function2";
}
}
module.exports = new TestClass();
Run Code Online (Sandbox Code Playgroud)
app.js 看起来像这样:
const TestClass = require("./classes");
console.log( TestClass.Function1);
Run Code Online (Sandbox Code Playgroud)
只需继续向类添加更多函数,它们就会被导出:)
Wes*_*cio 13
如果您使用 ES6,您可以执行以下操作:
function bar() {
//bar
}
function foo() {
//foo
}
export default { bar, foo };Run Code Online (Sandbox Code Playgroud)
小智 10
我做了类似以下的事情:
var Exported = {
someFunction: function() { },
anotherFunction: function() { },
}
module.exports = Exported;
Run Code Online (Sandbox Code Playgroud)
我在另一个文件中需要它,我可以访问这些功能
var Export = require('path/to/Exported');
Export.someFunction();
Run Code Online (Sandbox Code Playgroud)
这基本上只是一个包含函数的对象,然后导出对象.
值得注意的是,在ES6中,您现在可以导出如下函数:
export function foo(){}
export function bar(){}
function zemba(){}
Run Code Online (Sandbox Code Playgroud)
只需export在要导出的功能之前写入.更多信息在这里.
小智 5
const fs = require("fs")
var ExportAll = {
deleteFile : function deleteFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
fs.unlinkSync(imagePath)
}
},
checkFile : function checkFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
return true
}
else{
return false
}
},
rand : function(min=1,max=10)
{
return Math.floor((Math.random() * max) + min)
}
}
module.exports = ExportAll
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20072 次 |
| 最近记录: |