Modules
The concept of modules first appeared in the ECMAScript 2015 standard. Modules allow you to split a complex application into separate files, each of which contains strictly defined functionality, and then, using import, to put them together. Variables, classes, functions declared in a module are not available from outside this module, unless they are exported using the export
command. And in order to use the exported parts in another module, you need to import them using the import
command.
Export
Any declaration can be exported using the export
keyword.
// Экспорт переменной
let fruit: string = 'banana',
device: string = 'smartphone',
bool: boolean = true
export { fruit, device, bool as isBool }
// Экспорт константы
export const e = 2.7182818284590452353602874713526625
// Экспорт функции
export function sum(x, y: number): number {
return x + y
}
// Экспорт интерфейса
export interface Fruit {
name: string;
sweetness: number;
bones: boolean;
}
// Экспорт класса
export class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`)
}
}
// Экспорт всего сразу
export { fruit, e, sum, Fruit, Animal }
Default export
Using the keyword default
you can export by default.
export default class User {
constructor(public name) {}
}
Import
You can connect the exported functionality of the module using the keyword import
.
// Импорт пример
import { A, B } from './scripts'
// Импорт для экспорта по умолчанию
import User from './users'
// Импорт с другим именем
import { A as a, B } from './scripts'
// Импорт всех модулей
import * as scripts from './scripts'
let a = scripts.A
Re-export
In a module, you can re-export the functionality of some other module using the export .. from
construction. In this case, no import is performed locally and the variable is not created.
export { B as b } from './scripts'
Questions
Now we are ready to study TypeScript with you, but in order to understand how much you learned this lesson, take the test in the mobile application in our school on this topic.
Links
Contributors ✨
Thanks goes to these wonderful people (emoji key):
IIo3iTiv | Dmitriy Vasilev 💵 |