Convert import() to synchronous

2020-08-15 01:51发布

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

3条回答
老娘就宠你
2楼-- · 2020-08-15 02:10

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

查看更多
Evening l夕情丶
3楼-- · 2020-08-15 02:17

You can still use require() function by using this babel plugin https://www.npmjs.com/package/babel-plugin-dynamic-import-node-sync

查看更多
Root(大扎)
4楼-- · 2020-08-15 02:29

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');
查看更多
登录 后发表回答