I have a file, which must be loaded asynchronously, so I made a function, which loads this file and returns the Promise
:
export function load() {
// ...
return import(filename);
}
What is the return type of this Function? Promise<any>
works, but it feels very weird. I'd like to write the signature as.
export function load() -> Promise<???>;
Dynamic import of modules It returns a promise and starts an asynchronous task to load the module. If the module was loaded successfully, then the promise resolves to the module content, otherwise, the promise rejects.
Dynamic imports or Code Splitting is the practice of breaking up your JavaScript modules into smaller bundles and loading them dynamically at runtime to improve and increase the performance of your website dramatically.
Unlike static imports, React's dynamic imports don't bundle the module at compile time. Rather, when the component is about to render for the first time, React will resolve the promise and load the corresponding module, swapping it in as the app is running.
Dynamic module imports play a very important role if you want your code to be fast and more performant. Most of the time, you don't have to load all those heavy and bulky files in one go. It will be super helpful if we can somehow import those files whenever they are required.
You need to use an import type and TypeScript 2.9 or higher. Here is an example:
export const user = { name: "John", age: 30 };
export const event = { name: "Birthday", date: new Date(1989, 13, 2) };
type ModuleType = typeof import("./my_module"); // This is the import type!
export function load(): Promise<ModuleType> {
// ...
return import("./my_module");
}
(async () => {
const module = await load();
console.log(module.user.age); // It works!
})();
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": [
"es2015",
"dom"
],
"strict": true,
"esModuleInterop": true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With