如何使用方法和属性导出对象

How to export an object with methods and properties

我在 Electron(使用 Nodejs)中有两个 js 文件,我尝试从一个导出并在另一个中要求。

app.js:

App = {
 server: {
   host: '192.168.0.5',
   user: 'root',
 }
 ping: function() {
 }
}

exports.App = App

我已经尝试了所有可能的导出方式,包括module.exports = Appmodule.exports.App = App等等。

ping.js 第一次尝试:

var App = require('../app.js') // I have also tried adding .App to the end
console.log(App) // This returns an object which contains the App object

ping.js 第二次尝试:

var App = require('../app.js')
App.x = 'y'
console.log(App) // this returns an object which contains the App object and the x property

似乎 App 包含另一个 App 对象,但 console.log(App.App) 说它不存在。

解决这个问题的第一件事是确保我使用了所需模块的完整路径,如:

const Path = require('path')
const App = require(Path.join(__dirname,'../app')) // the .js isn't needed here.

请注意,这假定 app.js 文件位于应用程序运行所在目录的直接父目录中。

如果这不起作用,我会确保文件位于您认为的位置,并且您 运行 所在的进程位于您认为的文件系统中。您可以通过将其添加到主脚本文件的顶部来确定这一点:

console.log("current working directory:",process.cwd())

或者在 es6 中:

console.log(`current working directory: %s`, process.cwd())

如果打印的目录与您的假设不符,请相应地修改您的 require 语句。

郑重声明,"correct" 导出应用地图的方法是:

const App = {
  ... 
}
module.exports = App

或者使用 es7:

export default App = {
  ...
}

(有关 es7 模块的更多信息,请参阅 export。)

无论哪种方式,您都需要模块:

const App = require(PATH_TO_APP)