liveBook · Manning

Import statement

As explained in Essential TypeScript 5, Third Edition

An import statement is JavaScript module syntax that declares dependencies on exported bindings from another module.

An import statement declares a dependency on another module. It makes an exported function, class, or value available under a name in the importing file. In JavaScript, a function imported from `./tax.js` can then be called like a locally defined function. section 4.5.3

Default and named imports

In `index.js`, `import calcTax from "./tax.js";` imports a default feature. For named exports, put the required names in braces: `import { printDetails, applyDiscount } from "./utils.js";`. A statement can combine both forms: `import calcTaxAndSum, { calculateTax } from "./tax.js";`. Named imports need only list features the file uses. section 4.5.3 section 4.5.5

The location after `from` matters. A path beginning with `.` or `..` points to a module in the project, relative to the importing file. Without that prefix, the import refers to a module outside the local project; where tools search for it depends on the framework and build tools. section 4.5.3

Write the path for the generated JavaScript

In a Node.js ECMAScript-module project, `src/index.ts` can use `import { sum } from "./calc.js";` even though the source file is `src/calc.ts`. Include the generated JavaScript file’s extension, not `.ts`: TypeScript does not rewrite import paths for the runtime. Set `"type": "module"` in `package.json` and configure the compiler for the intended module format. Otherwise, emitted import syntax can fail with `Cannot use import statement outside a module`. section 2.3.1 section 5.8

An import need not name a binding. In a React app, `import 'bootstrap/dist/css/bootstrap.css';` includes an installed stylesheet; the same entry file also imports React, the app component, and local CSS. section 20.1.2

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains default and named imports, module locations, and Node.js path and format failures; does not detail every import form.
Examples
Uses tax and utility functions, imported TypeScript classes, a compiler error, and a React stylesheet dependency.
What it assumes
Assumes familiarity with JavaScript functions and files while explaining module dependency syntax and relative paths.
What you can do after
Build it from scratch: write default or named imports and choose runtime-compatible paths for a Node.js TypeScript project.
How it connects
Connects imports to exports, ECMAScript modules, CommonJS modules, TypeScript compiler configuration, and Node.js module loading.

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 Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.