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
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()
})()