Home > OS >  What's the simplest way to call an exported function?
What's the simplest way to call an exported function?

Time:08-13

I have a module dotenv which has a function config that I need to call once, first thing when the code runs. With CommonJS, I could do:

require('dotenv').config()

But with ECMAScript, I have to do the following:

import { config } from 'dotenv'
config()

Right now I also have this config function which I will never use again. Is there a better way to call the function?

CodePudding user response:

You can try a async import and execute the imported config directly. Something like:

// say [yourConfigLibrary] exports
// export default { config: _ => ({a: 1, b: 2, c: 3, configDone: true,}) };
// then you can import and run it in one line:
const config = (await import(`[yourConfigLibrary]`)).default.config();

See this stackblitz snippet, same for nodejs

CodePudding user response:

I should've done a bit of research before asking the question, it seems like there is no better way.

  • Related