2017-04-11 36 views
0

我在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)說,它不存在。

回答

1

我倒是做的解決,這將是確保我使用所需模塊的完整路徑,如第一件事:

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聲明。

並記錄在案, 「正確」 的方式來導出您的應用程序映射將是:

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

或者用ES7:

export default App = { 
    ... 
} 

(見export更多關於ES7模塊。 )

無論哪種方式,你會然後要求模塊:

const App = require(PATH_TO_APP) 
+0

我發現了這個問題。我使用index.html中的require('app.js')',但'ping.js'只需要'app.js'。我在index.html中添加了require('ping.js')'並且它工作正常。 – Alex

相關問題