Modules: import, export and types
A real program does not fit in a single file. Modules let you split it: each file exposes what it wants to share with export and takes what it needs from others with import. TypeScript uses the same ECMAScript module syntax as modern JavaScript and adds a type layer on top. A file is considered a module as soon as it contains at least one top-level import or export; without them, its declarations are global, which usually causes name conflicts.
Exporting and importing
You can export functions, constants, classes, types and interfaces, and import them by name between braces. There is also the default export, but named exports are preferable: autocompletion discovers them and renaming them is safer. To import types, use import type, which guarantees that line is completely erased when compiling and makes clear to the reader that it is not a value. With the verbatimModuleSyntax option, the compiler forces you to do it this way.
// src/models.ts
export interface Task {
id: number;
title: string;
done: boolean;
}
export type TaskFilter = 'all' | 'done' | 'pending';
// src/tasks.ts
import type { Task, TaskFilter } from './models.js';
export function filterTasks(tasks: Task[], filter: TaskFilter): Task[] {
if (filter === 'all') {
return tasks;
}
return tasks.filter((t) => (filter === 'done' ? t.done : !t.done));
}
export const DEFAULT_FILTER: TaskFilter = 'all';
// src/index.ts
import { filterTasks, DEFAULT_FILTER } from './tasks.js';
import type { Task } from './models.js';
const list: Task[] = [{ id: 1, title: 'Write', done: false }];
console.log(filterTasks(list, DEFAULT_FILTER));Why './models.js' and not './models.ts'
With moduleResolution NodeNext, which is correct for Node.js, relative import paths must carry the extension of the file that will exist at runtime. Since the compiler generates models.js, you write './models.js' even though the source file is models.ts. It clashes at first, but it is consistent: TypeScript does not rewrite your paths, and what you write is exactly what Node will see. For npm packages no extension is needed; for your own files it is.
For Node to treat your files as ES modules, add "type": "module" to package.json. With that option, import works natively and the compiled output can be run with node dist/index.js. Without it, Node interprets .js files as CommonJS and, with module NodeNext, TypeScript compiles import to require. Both worlds work, but it is best to choose one and stick to it.
{
"name": "ts-course",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "tsc",
"check": "tsc --noEmit",
"start": "node dist/index.js",
"dev": "tsx src/index.ts"
}
}To organize a project well, follow a simple rule: each file has one responsibility and exports only what others need. Keep helper functions private simply by not exporting them. You can create an index.ts file in a folder that re-exports the public parts with export { something } from './something.js', so that those who import only know the folder. Avoid star imports unless you really need the whole module as an object. A clear order in imports, first Node ones, then packages and finally your own, also helps reading.
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов