Home > front end >  Construct an array with ES6-style imports
Construct an array with ES6-style imports

Time:09-26

I am trying to convert some Node javascript code to typescript, which means converting require()s to imports.

Here is the original javascript:

const stuff = [
    require("./elsewhere/part1"),
    require("./elsewhere/part2"),
    // ...
];

Node-style require()s return an object, but ES6-style imports don't:

import part1 from "./elsewhere/part1"
// ...

const stuff = [ part1, /* ... */];

What can I do to retain the clean look of the original javascript in typescript?

Thank you for your time.

CodePudding user response:

I think your only option would be to use dynamic imports instead, since they return a Promise, but it has the drawback of making everything asynchronous, even if it isn't:

const stuff = await Promise.all([
    import("./elsewhere/part1"),
    import("./elsewhere/part2"),
    // ...
]);

I'd prefer your original version of static imports.

  • Related