这是In Node.js, how do I "include" functions from my other files?
的后续问题我想包含一个外部js文件,其中包含node.js app的常用功能。
根据In Node.js, how do I "include" functions from my other files?中的一个答案,可以通过
完成// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
导出每个功能都不方便。是否可以使用单行程输出所有功能?看起来像这样的东西;
module.exports = 'all functions';
这种方式更方便。如果以后忘记导出某些功能,也会减少错误。
如果不是单行,是否有更简单的替代品使编码更方便?我只想方便地包含一个由常用函数组成的外部js文件。类似于C / C ++中的include <stdio.h>
。
答案 0 :(得分:20)
您可以先编写所有函数声明,然后将它们导出到对象中:
function bar() {
//bar
}
function foo() {
//foo
}
module.exports = {
foo: foo,
bar: bar
};
虽然没有神奇的单行,但您需要明确导出您想要公开的功能。
答案 1 :(得分:6)
我做了类似以下的事情:
var Exported = {
someFunction: function() { },
anotherFunction: function() { },
}
module.exports = Exported;
我在另一个文件中需要它,我可以访问这些功能
var Export = require('path/to/Exported');
Export.someFunction();
这实际上只是一个包含函数的对象,然后导出对象。
答案 2 :(得分:6)
值得注意的是,在ES6中,您现在可以导出如下函数:
export function foo(){}
export function bar(){}
function zemba(){}
只需在要导出的函数前写export
即可。更多信息here。
答案 3 :(得分:4)
import React from "react";
import "./style.css";
export default class App extends React.Component {
divRef;
constructor(props){
super(props)
this.divRef = React.createRef();
}
toggleView = (e) => {
e.preventDefault();
const element = e.currentTarget.parentElement.classList;
if(element.contains("active")){
element.remove("active");
return;
}
element.add("active");
}
render(){
return (
<div class="parent">
<div ref={this.divRef}>
1
<a href="#" onClick={(e) => this.toggleView(e)}>toggle</a>
</div>
<div ref={this.divRef}>2
<a href="#" onClick={(e) => this.toggleView(e)}>toggle</a>
</div>
</div>
);
}
}
答案 4 :(得分:3)
一个非常老的问题,但是我只需要自己解决同样的问题。 我使用的解决方案是在模块内部定义一个Class来包含我的所有函数,然后简单地导出该类的实例。
classes.js看起来像这样:
class TestClass
{
Function1() {
return "Function1";
}
Function2() {
return "Function2";
}
}
module.exports = new TestClass();
app.js看起来像这样:
const TestClass = require("./classes");
console.log( TestClass.Function1);
只要继续向类中添加更多函数,它们就会被导出:)
答案 5 :(得分:1)
如果您使用ES6,则可以执行以下操作:
function bar() {
//bar
}
function foo() {
//foo
}
export default { bar, foo };
答案 6 :(得分:1)
从具有导出函数的类型模块文件中导入所有内容。
在此处找到: https://javascript.info/import-export
myfile.js
export function myFunction()
{
// ................
}
export function myFunction2()
{
// ................
}
myfile2.js - 导入文件中导出的所有内容
import * as myFunctions from './myfile.js';
// Usage
myFunctions.myFunction();
myFunctions.myFunction2();