![]() |
TypeScript, a superset of JavaScript, brings static typing to JavaScript, which enhances code quality and maintainability. One of the powerful features supported in TypeScript and modern JavaScript is the ability to conditionally or lazily load modules using dynamic import expressions. This feature is useful for optimizing application performance by loading code only when it is needed. What are Dynamic Imports?Dynamic imports allow you to import modules at runtime rather than at compile time. This is achieved using the import() function, which returns a promise that resolves to the module object. This feature is part of the ECMAScript proposal and is supported in TypeScript. Syntax:import(moduleSpecifier) Setting Up TypeScript ProjectStep 1: Before running the examples, ensure you have a TypeScript project set up. If not, you can initialize one with the following commands. mkdir TS Step 2: Navigate to that directory cd dynamic-imports-example Step 3: Initiate the package npm init -y Step 4: Install the required dependencies npm install typescript @types/node --save-dev Step 5: Initiate the Typescript project npx tsc --init Step 6: Create a tsconfig.json File: Ensure tsconfig.json is properly configured to include the esnext module system and other necessary options {
"compilerOptions": {
"target": "es6",
"module": "esnext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"include": ["src"]
} Project Structure:![]() Step 7: we will setup the conditional import. Conditional ImportsDynamic imports are useful when you need to conditionally load a module based on some runtime condition. This can be beneficial for loading feature-specific code only when certain conditions are met. Syntax:if (condition) {
import('./modulePath').then(module => {
// Use the module
});
} Example: This example shows the dynamic import of TypeScript file.
Output: Feature module initialized. TypeScript and Dynamic ImportsTypeScript fully supports dynamic imports and provides type safety for the imported modules. You can use the typeof operator to get the type of the imported module. Syntax:import('./modulePath'); Example: This example shows the dynamic simple import of the TypeScript file.
Output: Typed module function called. Step 8: run the code tsc index.ts Note: The command will generate or compile the TypeScript file, if it get compiled into JavaScript file then you can run that file using ” node index.js” to get the output. else the output will be shown directly. |
Reffered: https://www.geeksforgeeks.org
TypeScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 19 |