0

I am new to node js, while going through few bogs and tutorials I came across one thing different way to import module

For some people use:

const {app} = require('./routes/index');

Few sites follow:

 const app= require('./routes/index');

So what is difference between first and second, I am really confused with this and didn't get any proper explanation about this

faraz
  • 223
  • 2
  • 11

1 Answers1

5

Short Answer

const app = require('./routes/index');

imports the default value or everything at once from that file

const { app, app2 } = require('./routes/index');

imports specific object/s from that file.


LONG ANSWER

There are two ways to import something from ./routes/index.js.

The first one is,

const app = () => {
    console.log("Sample function")
}

// MOST IMPORTANT!
export default app
// Here, we are exporting app from that file as default. We use this normally, when we export only one thing from a file, and in this case, you can use,
const app = require('./routes/index')

As, only one object is getting exported, so you can use this, BUT!

  1. Second Case:-
const app = () => {
   console.log("Sample Function 1")
}

const app2 = () => {
   console.log("Sample Function 2")
}

export { app, app2 }
// Here, we are exporting two different objects/functions NOT as default. As there are two different object, you need to specify which one to import

Now, to import one of these function, we can use,

const { app2 } = require('./routes/index');
// OR
const { app } = require('./routes/index');
// OR
const { app, app2 } = require('./routes/index');

If you want to import both at once, you can also use,

const app = require('./routes/index')

// The first function can be accessed/called by,
app.app()
// or
app.app2()

But, as this makes it more confusing and takes up more memory, so we don't import all at once normally.

YTGS
  • 167
  • 1
  • 12