How to import external modules in TypeScript



Image not found!!

In TypeScript, you can import external modules using the import statement. Here's a basic example of how you can import modules:

Let's say you have a module defined in a file named myModule.ts:

typescript
// myModule.ts export const myVariable = 42; export function myFunction() { console.log('Hello from myFunction!'); }

Now, in another TypeScript file, you can import and use this module:

typescript
// main.ts import { myVariable, myFunction } from './myModule'; console.log(myVariable); // Outputs: 42 myFunction(); // Outputs: Hello from myFunction!

A few things to note:

  1. Make sure the file paths in the import statement are correct relative to the file making the import. In the example above, main.ts and myModule.ts should be in the same directory.

  2. TypeScript also supports default exports. For example:

typescript
// myModule.ts const myVariable = 42; function myFunction() { console.log('Hello from myFunction!'); } export default myVariable; export { myFunction };

And you can import it like this:

typescript
// main.ts import myVariable, { myFunction } from './myModule'; console.log(myVariable); // Outputs: 42 myFunction(); // Outputs: Hello from myFunction!
  1. Ensure that your tsconfig.json file is set up correctly to compile TypeScript modules. The "module" option should be set to "commonjs" or another module system of your choice.
json
{ "compilerOptions": { "module": "commonjs", // other options... }, // other configuration... }

These are the basics of importing external modules in TypeScript. Keep in mind that TypeScript relies on the module system used in JavaScript (CommonJS, AMD, UMD, ES6 modules, etc.), and your import syntax may vary depending on the module system you choose.