Convert import() to synchronous
Current versions of Node.js support top-level await behind the flag --harmony-top-level-await
(Node >= 13.2) or --experimental-top-level-await
(Node >= 14.3). When Node is launched with either of the flags, an import like
import fs from 'fs';
Can be re-written in CommonJS as
const fs = await import('fs');
You can still use require() function by using this babel plugin https://www.npmjs.com/package/babel-plugin-dynamic-import-node-sync
You can use deasync or node-sync to convert anything, including imports, to be synchronous - without blocking the whole node process.
Here is a plugin I wrote to do that: require-esm-in-cjs
Or you can block the entire process and load the package using require('child_process').execSync
. This is usually not recommended, but may be OK for compiling a local script, etc.
In addition, CommonJS supports async/await within a function. So in many cases you can do (which is async, but has synchronous function flow)
async function main(){
let mod = await import('my-module')
.catch(console.log);
// do something with mod...
}
main();
And, if you are using a ESM module, top level await() is now supported.
There is no way to do this currently with commonJS. Until there is some synchronous import()
or top-level await, this cannot be done.