0

Just wondering, am I able to import ES6 modules without creating a "placeholder" variable and run it immediately?

for instance, instead of ES6's import that creates an unused express variable:

import express from 'express' 
const app = express();

In CommonJS I can do it without it:

const app = require("express")();

This is particularly useful for one time only imports such as dotenv:

require("dotenv").config();

Instead of

import dotenv from 'dotenv'
dotenv.config();
//or
import {} from 'dotenv/config'
config()

Which I think CommonJS syntax is much cleaner, but it seems ES6 imports are the future.

Thanks

Jamie Phan
  • 796
  • 1
  • 7
  • 26

2 Answers2

1

There's no way for that in ES6, but there's a finshed (Stage 4) proposal for doing this:

(await import('dotenv')).config()

Or, if the target module doesn't provide named export:

(await import('dotenv')).default.config()

However, you should note that await can only be used inside an async function (until this another proposal gets implemented):

(async ()=>{
  (await import('dotenv'))/*.default*/.config()
})()
FZs
  • 16,581
  • 13
  • 41
  • 50
0

No, there is no way other than mentioning the placeholders(default export or export names) to import ES6 module.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Boney
  • 1,462
  • 1
  • 11
  • 19