Mastering the Parts: Importing Components in TypeScript Projects
- 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;
- Classes:
- 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
andpaths
: 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