liveBook · Manning

Import statement

As explained in Pro Angular 16

An import statement is JavaScript or TypeScript syntax that declares a dependency on another module and makes its exported declarations available in the current module.

An import statement declares that a JavaScript or TypeScript file depends on features from another module. Declarations in a file are not available to other files by default: they must first be exported, then imported where they are used. section 4.5.1

Importing a data model

A to-do list class can use `import { TodoItem } from "./todoItem";` to access the exported `TodoItem` class. Its component can then import both `TodoItem` and `TodoList` to create sample data for a template. section 2.3.1 section 2.3.3

Read the statement from left to right:

  • The names in `{ ... }` identify the exported features needed by the current file. Separate multiple names with commas. section 4.5.1
  • The name after `from` identifies the module. A path beginning `./` is relative to the current file; `@angular/core` names an Angular package module. section 2.3.3
  • The module name omits the file extension. Angular’s build tools resolve the dependency and include required code in the JavaScript bundle sent to the browser. section 2.3.3 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);

The complete `main.ts` example imports two exported classes from one module, creates an instance of each, and logs their messages. section 4.5.1

Importing an Angular component brings its class into scope, but does not by itself enable that component in the application. The component is also added to an Angular module’s `declarations` array, and a matching host element is placed in a template. section 16.2.1

How Pro Angular 16 covers it

How deep it goes
Explains named-import syntax, relative module paths, omitted extensions, and bundle inclusion; defers fuller build-tool details.
Examples
Uses a to-do data model and a file that imports two classes to print messages in the browser console.
What it assumes
Introduces module-local declarations and exports before imports while working with TypeScript classes and Angular project files.
What you can do after
Apply it via Angular development tools to use exported classes across files and include their required code in the browser bundle.
How it connects
Connects imports to module scope, exports, Angular components, NgModule declarations, and JavaScript bundles.

Also explained in

Compare how 13 books explain import statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.