【问题标题】:How to export an object with methods and properties如何导出具有方法和属性的对象
【发布时间】:2017-09-07 09:06:03
【问题描述】:

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

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) 说它不存在。

【问题讨论】:

    标签: javascript node.js export electron require


    【解决方案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 = {
      ...
    }
    

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

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

    const App = require(PATH_TO_APP)
    

    【讨论】:

    • 我发现了问题。我使用的是 index.html 中的require('app.js'),但只有app.js 需要ping.js。我在 index.html 中添加了require('ping.js'),它起作用了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多