Import/export syntax organizes JavaScript and TypeScript files as modules. Files are self-contained by default; export makes selected classes, functions, or variables available elsewhere, while import declares a dependency on those features. section 4.5.1 section 2.3.1
Use named imports in curly braces, separate multiple features with commas, follow them with from and the module name, and omit the .ts file extension. Build tools follow the dependency and include the needed module in the browser bundle. section 4.5.1
Export classes and import them
A module can expose two classes, while another file imports and uses only those named exports. The resulting program creates a greeting and a weather message for the console. section 4.5.1
Share a data model
Export TodoItem from todoItem.ts, then import it into todoList.ts. TodoList can construct TodoItem instances while keeping the model in a separate module. section 2.3.1
Listing 4.28. The contents of the NameAndWeather.ts file in the src/modules folder
export class Name {
constructor(public first: string, public second: string) {}
get nameMessage() {
return `Hello ${this.first} ${this.second}`;
}
}
export class WeatherLocation {
constructor(public weather: string, public city: string) {}
get weatherMessage() {
return `It is ${this.weather} in ${this.city}`;
}
}
Inspect a complete module that exports two classes and exposes their public behavior to importing code. section 4.5.1
Listing 4.29. Importing specific types in the main.ts file in the src folder
import { Name, WeatherLocation } from "./modules/NameAndWeather";
let name = new Name("Adam", "Freeman");
let loc = new WeatherLocation("raining", "London");
console.log(name.nameMessage);
console.log(loc.weatherMessage);
Inspect the corresponding import statement and the code that instantiates the exported classes. section 4.5.1




