Javascript将main.js拆分为两个文件(导入?需要吗?)

Javascript将main.js拆分为两个文件(导入?需要吗?),javascript,node.js,Javascript,Node.js,我的超长文件(main.js)可以正常工作。但我想将处理“y”的函数拆分为一个单独的文件,以供组织使用。在PHP中,我将使用require('yfunctions.PHP')并完成它 javascript中是否存在不需要重写函数调用的等价物 main.js: // do stuff function first(x){ // do stuff with x } function second(y){ // do stuff to y // return y } function

我的超长文件(main.js)可以正常工作。但我想将处理“y”的函数拆分为一个单独的文件,以供组织使用。在PHP中,我将使用require('yfunctions.PHP')并完成它

javascript中是否存在不需要重写函数调用的等价物

main.js:

// do stuff

function first(x){
  // do stuff with x
}

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}
require('yfunctions.js');
// do stuff

function first(x){
  // do stuff with x
}
最终成为:

main.js:

// do stuff

function first(x){
  // do stuff with x
}

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}
require('yfunctions.js');
// do stuff

function first(x){
  // do stuff with x
}
yfunctions.js:

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}
上述方法似乎不起作用。我是否必须向yfunctions.js中的每个函数添加“导出”声明?难道没有办法说“将此文件中的每个函数作为函数导出”吗


(注意,我正在使用node.js/electron…但我很想了解javascript的工作原理。)

使用
module.exports来导出模块的成员。在您的示例中:

module.exports.second = second;
module.exports.third = third; 
function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}
没有自动导出模块所有成员的选项

如果您在ES6中工作,以上内容可以简化为:

module.exports = {
    second,
    third
};

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}

在这种情况下,您必须使用模块导出,并使用require导出其他存档中的函数。在您可以使用之后,请检查我的示例

functions.js

module.exports = {
  foo: function () {
    // do something
  },
  bar: function () {
    // do something
  }
};

var tryit = function () {
}
var callFunction = require('./functions');
console.log(typeof callFunction .foo); // => 'function'
console.log(typeof callFunction .bar); // => 'function'
console.log(typeof callFunction .tryit); // => undefined because does not use exports
使用functions.js中的函数

module.exports = {
  foo: function () {
    // do something
  },
  bar: function () {
    // do something
  }
};

var tryit = function () {
}
var callFunction = require('./functions');
console.log(typeof callFunction .foo); // => 'function'
console.log(typeof callFunction .bar); // => 'function'
console.log(typeof callFunction .tryit); // => undefined because does not use exports

啊。。。所以如果我要拆分50个函数,我必须有一个50个module.exports的列表?似乎是多余和乏味的(并且鼓励我只制作一个怪物长的main.js文件…@Trees4theForest-这是正确的
module.exports
和较新的(尽管目前基本上不支持)ES6
export
在很大程度上基于所谓的()。在大多数情况下,您会尝试导出尽可能少的函数,并将任何特定于实现的函数隐藏在模块本身中,从而创建一种“公共API”。如果您使用的是一个合理的文本编辑器,那么您可能有重构工具来帮助这个过程,如果没有,一个足够简单的正则表达式就可以为您获取这些工具。如果唯一的障碍是收集50个函数名,我建议您将节点软件模块化。