Mastering the Parts: Importing Components in TypeScript Projects

2024-07-27

  • Before you import something, it needs to be exported from the original file. This makes it available for other files to use.
  • You can export various things using the export keyword:
    • Classes: export class MyClass { ... }
    • Functions: export function sayHello() { ... }
    • Variables: export const PI = 3.14;
  • You can export either individual items or everything using export *.
  • Once something is exported, you can import it into another TypeScript file using the import statement.
  • The basic syntax is:
    import { whatToImport } from './path/to/file';
    
    • whatToImport: This can be a specific item (class, function, variable) or * to import everything.
    • ./path/to/file: This is the relative path to the file you're importing from. The path is relative to the current file.

Here's an example:

File: math.ts (Exported file)

export function add(x: number, y: number): number {
  return x + y;
}

export const PI = 3.14;
import { add, PI } from './math';

console.log(add(2, 3)); // Output: 5
console.log(PI);        // Output: 3.14

Additional Points:

  • You can rename imported items using an alias:
    import { add as sum } from './math';
    console.log(sum(2, 3));  // Output: 5
    
  • Importing everything with import * is generally discouraged as it can lead to naming conflicts.



export class User {
  constructor(public name: string, public age: number) {}

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}
import { User } from './user';

const user1 = new User("John Doe", 30);
user1.greet(); // Output: Hello, my name is John Doe and I am 30 years old.

Importing a function with renaming:

export function multiply(x: number, y: number): number {
  return x * y;
}
import { multiply as product } from './utils';

const result = product(5, 4);
console.log(result); // Output: 20

Importing a variable:

export const API_URL = "https://api.example.com";
import { API_URL } from './config';

fetch(API_URL)
  .then(response => response.json())
  .then(data => console.log(data));



While not directly importing files, the tsconfig.json file plays a crucial role in how TypeScript handles imports. Here's how it can be used:

  • baseUrl and paths: This configuration allows you to define a base directory and mappings for commonly used paths. This can simplify imports by avoiding long relative paths.

Example:

```json
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@components/*": ["components/*"]
    }
  }
}
```

With this configuration, you can import a component like this:

```typescript
import MyComponent from "@components/MyComponent";
```

Dynamic Imports (ES Modules):

  • Introduced in ECMAScript 2015 (ES6), dynamic imports allow you to import modules at runtime. This can be useful for lazy loading code that isn't needed immediately.

Syntax:

```typescript
const module = await import('./lazyLoadedModule');
const someFunction = module.default; // Assuming default export
```

Note: Dynamic imports are not supported in older environments and require additional bundling configuration.

Non-TypeScript Approaches (Limited Use):

  • In rare cases, if you're working with a mix of TypeScript and JavaScript files, you might consider using the older CommonJS require function. However, this is generally discouraged for new projects as it's not type-safe.

Important points to remember:

  • The standard import statement with relative or absolute paths is the recommended approach for most modern TypeScript projects.
  • tsconfig.json configuration can improve import readability and maintainability.
  • Dynamic imports have specific use cases and require additional setup.
  • Avoid non-TypeScript approaches like require unless absolutely necessary.

typescript



Understanding Getters and Setters in TypeScript with Example Code

Getters and SettersIn TypeScript, getters and setters are special methods used to access or modify the values of class properties...


Taming Numbers: How to Ensure Integer Properties in TypeScript

Type Annotation:The most common approach is to use type annotations during class property declaration. Here, you simply specify the type of the property as number...



typescript

Understanding TypeScript Constructors, Overloading, and Their Applications

Constructors are special functions in classes that are called when you create a new object of that class. They're responsible for initializing the object's properties (variables) with starting values


Alternative Methods for Setting New Properties on window in TypeScript

Direct Assignment:The most straightforward method is to directly assign a value to the new property:This approach creates a new property named myNewProperty on the window object and assigns the string "Hello


Alternative Methods for Dynamic Property Assignment in TypeScript

Understanding the Concept:In TypeScript, objects are collections of key-value pairs, where keys are property names and values are the corresponding data associated with those properties


Alternative Methods for Type Definitions in Object Literals

Type Definitions in Object LiteralsIn TypeScript, object literals can be annotated with type definitions to provide more precise and informative code


Alternative Methods for Class Type Checking in TypeScript

Class Type Checking in TypeScriptIn TypeScript, class type checking ensures that objects adhere to the defined structure of a class