Connor Black
Connor Black

Reputation: 7181

Exporting Objects with the Exports Object

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 the same directory. Can I simply export this object with the module.exports object and require() it in the other .js file? If this is possible can you give me an example?

If it helps I'm developing with node.

Upvotes: 31

Views: 89705

Answers (7)

Jatin sharma
Jatin sharma

Reputation: 324

You can Export object in JavaScript like this

// global/styles.js

export const borderStyles = {
  border: "2px solid black",
  color : "#000"
};

and you can import it like the following

import { borderStyles } from "../../global/styles"

Upvotes: 4

Karthikeyan Ganesan
Karthikeyan Ganesan

Reputation: 2035

You can export object like

modules.js

export const events = {};
events.click = function (param1, param2...) {
    //do something here
}
events.change = function (param1, param2...) {
    //do something here
}
events.get = function (key, response) {
    //do something here
    response({status: "success"})
}

In main.js

import {events} from "./modules"
console.log(events)

Now you can use the Objects

events.get("my_key", (resp) => { 
  console.log(resp) // {status: "success"}
})

Upvotes: 1

Diptesh Mukherjee
Diptesh Mukherjee

Reputation: 21

as per es6 :-

const person = function(name){
  console.log(`Name of the person is ${name}`);
}

export default person;

Upvotes: 2

OhadR
OhadR

Reputation: 8849

the simplest approach, in my opinion:

write Person.js: (note it comes with ctor)

module.exports = function (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function () { 
        return this.firstName + ' ' + this.lastName;
    }
}

and consume it:

var person = require('./Person.js');

var person1 = new person('James', 'Bond');

console.log(person1.fullName());

note that in this simple solution all methods are "public".

ref: https://www.tutorialsteacher.com/nodejs/nodejs-module-exports

Upvotes: 3

Vahid PG
Vahid PG

Reputation: 428

Of course you can. In my example I use obj to hold my config info. I put it in a file called index.js in config folder. This makes the index the preferred choice to be picked when I import 'config'. I have 2 exports here one for my node and api stuff and the other for my db. You can ignore the first bit where I set the environment.

const environment = {
  development: {
    isProduction: false
  },
  production: {
    isProduction: true
  }
}[ process.env.NODE_ENV || 'development' ];

export default Object.assign({
  host: 'localhost',
  port: '3000',
  remoteApi: {
    token: {
      'X-Token': '222222222222222222'
    },
    base: 'https://www.somedomain.com/api'
  }
}, environment);

export const db = {
  dbHost: 'localhost',
  dbPort: 176178
};

Calling import config from '../config'; will pick the default one. And if I specify I can get the db export import { db } from '../config';

Upvotes: 11

c0deNinja
c0deNinja

Reputation: 3986

This is the way I create modules:

myModule.js

var MyObject = function() {

    // This is private because it is not being return
    var _privateFunction = function(param1, param2) {
        ...
        return;
    }

    var function1 = function(param1, callback) {
        ...
        callback(err, results);    
    }

    var function2 = function(param1, param2, callback) {
        ...
        callback(err, results);    
    }

    return {
        function1: function1
       ,function2: function2
    }
}();

module.exports = MyObject;

And to use this module in another JS file, you can simply use require and use your object as normal:

someFile.js

var myObject = require('myModule');

myObject.function1(param1, function(err, result) { 
    ...
});

Upvotes: 35

JoshRagem
JoshRagem

Reputation: 595

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)

Upvotes: 5

Related Questions