Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert import() to synchronous

I'm trying to convert all of my node require()s into the import() statements, however, those are async and I'm having a bit of trouble.

Right now I have:

import * as fs from 'fs';

const paths = fs.readdirSync('./src/modules').map(path => './modules/' + path.slice(0, path.length - 3));

const classes = [];

paths.forEach(path => {
    let bClass = require(path);

    try {
        classes.push(new bClass.default());
    }
    catch (err) {
        //Here for if no default import
    }
});

and want to convert that require(path) part into an import() but still want to keep it synchronous, is that possible? If it is, how would I got about it?

Edit: a little more context. I have a list of modules that we want to import, and we're doing it this way so if something bugs out with one module we can just comment it out / remove it and not have to recode everything else. I just need dynamic synchronous imports without using require().

like image 718
R. Gillie Avatar asked Jun 27 '18 18:06

R. Gillie


People also ask

Is ES6 import synchronous?

ES6 modules aren't asynchronous, at least not as they are in use right now most places.

Does import return a promise?

It returns a promise which fulfills to an object containing all exports from moduleName , with the same shape as a namespace import ( import * as name from moduleName ): an object with null prototype, and the default export available as a key named default .

What is difference between require and import?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .


1 Answers

There is no way to do this currently with commonJS. Until there is some synchronous import() or top-level await, this cannot be done.

like image 120
R. Gillie Avatar answered Oct 05 '22 09:10

R. Gillie