AI Hints
Home›Angular Tutorial›Decorators, import and export and Practice: Typed Books
Angular · Lesson 17 of 120

import and export

Code in many files.

⏱ 2 min read▶ Video at 20:49🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Real apps are split into many files. Each file is a module, and modules share code with import, and export.

  • Many files
  • Each file is a module
  • import and export

Sharing code

Export makes something in a file available to other files. Import brings it into another file, by name, from a path. A dot slash path means, a file in our project. And a package name, like at angular slash core, means a library.

keyvalue
exportshare it
import { X } from './file'use it
./booka file in our project
@angular/corea package

book.ts

Book dot ts exports three things. The Book interface, a VAT constant, and a function, with VAT.

book.tstypescript
export interface Book {
  title: string;
  price: number;
}

export const VAT = 0.2;

export function withVat(book: Book): number {
  return Math.round(book.price * (1 + VAT) * 100) / 100;
}

Using them in main.ts

Main dot ts imports all three, by name, from dot slash book. Then it uses them, as if they were written here. Run it. The VAT rate, and Emma's price with VAT, are printed.

main.tstypescript
import { Book, VAT, withVat } from './book';

const emma: Book = { title: "Emma", price: 6.99 };

console.log(`VAT rate: ${VAT * 100}%`);
console.log(`${emma.title} costs £${withVat(emma)} with VAT`);
Output
VAT rate: 20%
Emma costs £8.39 with VAT
Also uses book.ts
export interface Book {
  title: string;
  price: number;
}

export const VAT = 0.2;

export function withVat(book: Book): number {
  return Math.round(book.price * (1 + VAT) * 100) / 100;
}
Also uses _mode
ts

Summary

Export shares code from a file, and import uses it in another. Every Angular file starts with imports. Next, some practice.

Key takeaways
  • export
  • import { Book } from './book'
  • @angular/core
Next up: Practice: Typed Books — your turn