10

I'm working on something on NodeJS and I'm using the import keyword from the ES6 syntax.. and I want to execute immediately after calling it. I searched for similar thoughts to do that but nothing was helpful enough.

What I want to do is basically transform the following code from the CommonJS into the ES6.

// In CommonJS:
var birds = require('./birds')()

// In ES6:
import birds from './birds'()

I can do that using the const keyword:

import birds from './birds'
const SomethingButNotBirds = birds()

But, I really wanna know if there's a better way to do it.

I really appreciate your help guys!

YahiaRefaiea
  • 172
  • 1
  • 12

1 Answers1

11

ES6 import statement has a declarative syntax and does not give you room to execute functions just as you'd do with require()().

The code you have below is the only valid way of doing it.

import birds from './birds'
const SomethingButNotBirds = birds()
fortunee
  • 3,852
  • 2
  • 17
  • 29
  • Okay. it's fine actually to do so. But the only problem here is I won't be able to use the same variable I want. Do you think there's a better technic than: `import birdsRoutes from './birds'` `const birds = birdsRoutes()`. or something like: `const birds = require('./birds')()`. Think of it that you have a +15 routes under each other. What would you do? – YahiaRefaiea Feb 03 '18 at 02:37
  • You could try `import * as bd from './birds';` and use `const bird = bd.bird()` However, you should know that this has performance issues importing * imports all functions in birds – fortunee Feb 03 '18 at 02:41
  • **Looks possible!** I'll search for the `* as bd` syntax and I'll try it soon. Thanks for your help. – YahiaRefaiea Feb 03 '18 at 02:47
  • @YahiaRefaiea Alright. You can upvote my answer if it has somewhat helped you. – fortunee Feb 03 '18 at 02:48
  • Sorry buddy. I really did that. but, I have less than 15 reputation. so it didn't work – YahiaRefaiea Feb 03 '18 at 03:08
  • 1
    @FortuneEkeruo Your point about performance is not quite right. Both forms load the whole file, it just varies in how good your bundler is at telling if a given function is actually used or not. Plenty of them support the namespace version too safely. – loganfsmyth Feb 03 '18 at 03:18
  • Oh, I see! Thanks for pointing that out buddy, I'll research more about it. Thanks once again @loganfsmyth – fortunee Feb 03 '18 at 09:13