Exporting Objects with the Exports Object

后端 未结 4 1510
野趣味
野趣味 2021-02-02 14:36

Say I have one .js file containing a javascript object. I want to be able to access that object and all of its functionality from another .js file in t

4条回答
  •  后悔当初
    2021-02-02 14:52

    In one file:

    module.exports.myObj = some object...;
    

    In the other:

    Obj = require('myFile.js').myObj;
    

    Everything in a js file on node is local to that file unless you put it in the export object. This actually is very different from JavaScript in a browser--in the browser all files that get imported act together like one big file.

    You can kinda think about node files as though you are creating a module object and passing it' into a function surrounding your code.

    module = { 'exports' : {} };
    (function(module){
        //your js file
        ...
    })(module)
    

提交回复
热议问题