import and export: "type": "module", .ts extensions, import type
Split TaskKit's index.ts into four files that share boxes, functions and types with export and import. Learn the three rules Node follows on every import line: “type”: “module” in package.json, the whole file name with .ts, and import type for a type, which Node strips out before the program runs.
TypeScript
Fundamentals
`import` and `export`: `"type": "module"`, `.ts` extensions, `import type`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Module 8 left TaskKit's index.ts more than a hundred lines long.
To change what add does, you scroll past the two task types,
sameTask, printList, the banner, the summary, the command reader
and messageOf before the lines that run the command, the plan,
even start. Every feature you add makes the file longer, and finding
one function means reading past all the others.
Think of a shop. A customer can buy only what is on the counter, and
asks for it by its exact name; the store room behind stays private,
however full it gets. A file can work the same way. It puts a few
things on its counter with export, and another file asks for them
by name with import. By the end of this lesson TaskKit's program
is four files with one job each, and you know the three rules Node
follows when it reads an import line: one line in package.json
that says the files use import, the whole file name, and type in
front of a type.
One file, one job
In lesson 5.11 you moved three functions into tasks.ts so that a
test could reach them. export in front of a function shared it,
and import at the top of another file brought it in. That was
enough for a test. Now the same two words split a whole program.
A module is a file that keeps what it makes to itself, except
what it exports. Every .ts file in TaskKit is one. A box, a
function or a type made in a module belongs to that file alone, the
way a box made inside braces ends at their } (lesson 5.5), and
export in front of it is the only way out. So two files can each
have a box called limit, and neither ever sees the other's.
Three kinds of things can go on the counter. This file shares a
value, a type and a function:
shop.tsts
export const openingHour = 9;export type Aisle = "fruit" | "bread";export function greet(name: string): string { return `Welcome, ${name}`;}
export const shares a box, export type shares a type, and
export interface shares one too. The file that uses them names
what it wants between braces, spelled exactly as exported:
till.tsts
import { greet, openingHour } from "./shop.ts";
Ask for a name the file makes but does not export, and the check stops
you first: TS2459 (TS for TypeScript, then the number of the message),
as in lesson 5.11. Misspell a name, and the check says the file has no
exported member by that name, TS2724, and suggests the right one: Did you mean 'greet'?
Which kind of module: "type": "module"
Node knows two ways for files to share code. The one in this course,
with import and export, is called ES modules (ES for
ECMAScript, the official name of the JavaScript standard), and
every web browser uses it too. The other, CommonJS, is Node's
own older way, with a function called require. You will meet
require in older code; you will not write it.
Node wants to know which way a file is written before it reads it.
It looks for the answer in package.json, a JSON file: JSON, short
for JavaScript Object Notation, is plain data that tools read.
Lesson 5.11 put the answer there with npm pkg set type=module
(npm is the Node package manager, and pkg is short for package).
Open the file and you see the line it wrote:
Its first part lists the two tools npm installed in lessons 1.4 and
2.8, TypeScript and Node's types. Your version numbers may
differ.1"type": "module" says that every .ts and
.js file in this folder is an ES module. Without it, Node has to
guess: it first tries the CommonJS way, fails on the first import,
and reads the files again as ES modules. The program still runs, but
every run starts with the long MODULE_TYPELESS_PACKAGE_JSON
warning, so keep the line.
The whole file name, .ts included
The text after from is a path: ./ means "in this folder"
(lesson 5.11), and the rest is the file's name. Node
reads it exactly as written. It never tries adding .ts to a name
to see whether such a file exists, just as node hello could not
find hello.ts in lesson 1.3.
Bad — the path leaves out .ts, so
Node looks for a file called tasks, with no extension.
index.tsts
import { capitalize, percentFull, alphabetical } from "./tasks";
Good — the whole file name, so
Node opens tasks.ts.
index.tsts
import { capitalize, percentFull, alphabetical } from "./tasks.ts";
With the Bad line in index.ts, node index.ts add "pay rent"
prints more than a dozen lines, and not one of TaskKit's. The one
that matters starts with Error; in your terminal it is one line,
broken here to fit the page:
ERR_MODULE_NOT_FOUND is Node's code for "no file at that path"
(ERR is short for error). Read the path in quotes: it is where Node
looked, and it ends in tasks, not tasks.ts.
The trap is that the check passes with either line.
--allowImportingTsExtensions (lesson 5.11) lets TypeScript accept
a path that ends in .ts; it does not make TypeScript ask for one.
Lesson 9.4 adds the setting that does; until then, the .ts is
yours to write.
Types come in with import type
In a moment print.ts will hold printList, which takes a Task[],
and Task will live in tasks.ts. Lessons 7.6 and 8.2 showed that
Node strips every type out before it runs a file, leaving spaces in
its place (lesson 8.2). Here is what happens to
import { Task } from "./tasks.ts"; at the top of print.ts, and
to the same line with type after import. Switch between the
two, and press Next step to walk through each, or let it play:
TypeScript
Node
TaskKit
TypeScript: checked ✓checked✓checked✓
Node: strips typesstripstypesstripstypes
Node: keeps the linekeepsthelinekeepstheline
TaskKit: SyntaxErrorSyntaxErrorSyntaxError
Time
It finds Task in tasks.ts, a type it can read, so the check
passes both lines.
Before anything runs, every type turns into spaces: the two
types at the top of tasks.ts too.
Node cannot tell that Task is a type, so the line stays and
asks tasks.ts for it.
tasks.ts has no Task left to share, so Node stops before
the banner prints.
The check passes both lines; only import type gets past Node
All 4 steps shown.Step 1 of 4: TypeScript: checked ✓Step 2 of 4: Node: strips typesStep 3 of 4: Node: keeps the lineStep 4 of 4: TaskKit: SyntaxError
All 4 steps shown.
TypeScript
Node
TaskKit
TypeScript: checked ✓checked✓checked✓
Node: strips typesstripstypesstripstypes
Node: strips the linestripsthelinestripstheline
TaskKit: runs ✓runs✓runs✓
Time
It finds Task in tasks.ts, a type it can read, so the check
passes both lines.
Before anything runs, every type turns into spaces: the two
types at the top of tasks.ts too.
type says the whole line is about types, so it turns into
spaces with them.
Nothing asks for Task any more, and TaskKit prints its
banner and runs.
The check passes both lines; only import type gets past Node
All 4 steps shown.Step 1 of 4: TypeScript: checked ✓Step 2 of 4: Node: strips typesStep 3 of 4: Node: strips the lineStep 4 of 4: TaskKit: runs ✓
All 4 steps shown.
So a type gets a line of its own, marked with import type:
print.tsts
import type { Task } from "./tasks.ts";import { alphabetical, percentFull } from "./tasks.ts";
Two import lines from one file are normal: one for types, one for
values. To sort a name, look at the line that made it. A name made
by type or interface goes in import type; anything else, a
function or a const, goes in the plain import. The other way
round fails too, but on the check: a function brought in with
import type cannot be called, and TypeScript says so with TS1361,
'capitalize' cannot be used as a value because it was imported using 'import type'.
TaskKit's program in four files
Now TaskKit's step. index.ts does four jobs: it holds the task
types and sameTask, it prints, it reads the command, and it runs
the plan. The first three get files of their own, and index.ts
keeps the rest: messageOf and the plan.
1
Move the types and sameTask into tasks.ts
Cut type Status, interface Task and the function sameTask out
of index.ts, and paste them into tasks.ts: the two types at the
top, sameTask at the bottom. Put export in front of all three.
(id is short for identifier, the number that names one task.)
tasks.ts now reads:
tasks.tsts
export type Status = "todo" | "done";export interface Task { readonly id: number; title: string; due?: string; status: Status;}export function capitalize(task: string): string { return task.slice(0, 1).toUpperCase() + task.slice(1);}export function percentFull(added: number, limit: number): number { // Rounded: without it, a limit of 3 prints 66.66666666666666 return Math.round((added / limit) * 100);}export function alphabetical(a: string, b: string): number { return a.localeCompare(b);}export function sameTask(newTask: string): (task: string) => boolean { return (task) => task.toLowerCase() === newTask.toLowerCase();}
Until Step 4, VS Code (Visual Studio Code, your editor) marks
index.ts in red: it still uses names that have moved. That is
expected.
2
Make print.ts
Make a file called print.ts next to it, and start it with the two
import lines from the last section. Then cut printList,
printBanner and printSummary out of index.ts, paste them under
those lines, and put export in front of each. The top of the file:
print.tsts
import type { Task } from "./tasks.ts";import { alphabetical, percentFull } from "./tasks.ts";export function printList(tasks: Task[]): void {
3
Make command.ts
Make a file called command.ts, and cut type Command and the
function readCommand out of index.ts into it. Put export in
front of readCommand only: index.ts never writes the name
Command, so the type can stay private. command.ts needs no import
line: readCommand reads only process.argv (argv, short for
argument vector, the list of words you typed). The top of the file:
Replace the import line at the top of index.ts with these four.
percentFull and alphabetical leave its list, because only the
print functions use them now:
index.tsts
import { printBanner, printList, printSummary } from "./print.ts";import type { Task } from "./tasks.ts";import { capitalize, sameTask } from "./tasks.ts";import { readCommand } from "./command.ts";
5
Check, run TaskKit, run the tests
Check with tsc (short for TypeScript compiler), which npx
starts, then run TaskKit and the tests:
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call momTasks added: 2 of 5, room for 3 moreList 40% fullYour list, A to Z:#2 [todo] Call mom, due: not set#1 [todo] Pay rent, due: not set
The check prints nothing, though you named only index.ts:
TypeScript follows its import lines and checks command.ts,
print.ts and tasks.ts with it. TaskKit prints what it printed
before, and the tests end with fail 0.
What Node does with the import lines
Node does not start at line 1 of index.ts and work down. Before
it runs a single line of a file, it reads that file's import lines,
opens every file they name, and runs those first. Each import asks a
file for some names, and the file answers with what it exported.
Press Next step to follow it, or let it play:
index.ts
print.ts
tasks.ts
1
index.ts to print.ts: import{printBanner,…}
2
print.ts to tasks.ts: import{alphabetical,…}
3
tasks.ts, to itself: runs
4
tasks.ts to print.ts: alphabetical,percentFull
5
print.ts, to itself: runs
6
print.ts to index.ts: printBanner,…
7
index.ts to tasks.ts: import{capitalize,…}
8
tasks.ts to index.ts: capitalize,sameTask:nosecondrun
9
index.ts, to itself: runs,bannerfirst
Node follows the import lines first, and runs each file once
All 9 steps shown.Step 1 of 9: index.ts → print.ts — import { printBanner, … }Step 2 of 9: print.ts → tasks.ts — import { alphabetical, … }Step 3 of 9: tasks.ts — runsStep 4 of 9: tasks.ts → print.ts — alphabetical, percentFullStep 5 of 9: print.ts — runsStep 6 of 9: print.ts → index.ts — printBanner, …Step 7 of 9: index.ts → tasks.ts — import { capitalize, … }Step 8 of 9: tasks.ts → index.ts — capitalize, sameTask: no second runStep 9 of 9: index.ts — runs, banner first
All 9 steps shown.
print.ts cannot answer until its own import is answered, so
tasks.ts runs first, then print.ts. When index.ts asks
tasks.ts in turn, the second file to ask it, Node does not run the
file again: it hands over the names from the run that already
happened. A module runs once, however many files import it.
The last import line asks command.ts, which imports nothing, so it
runs at once and hands over readCommand; the picture leaves it
out. Only when every import line is answered does index.ts run its
own lines, starting with the banner. The import type lines are not in
the picture at all: by the time Node follows the imports, they are
spaces.
And since tasks.ts, print.ts and command.ts only make
functions and types when they run, they print nothing, so TaskKit's
output did not change.
Predict the order
These three files each print a line as soon as they run. They sit
in one folder, next to a package.json with "type": "module".
Follow the import lines the way Node does.
import { taskLimit } from "./limits.ts";console.log("room.ts runs");export function roomLeft(added: number): number { return taskLimit - added;}
index.tsts
import { taskLimit } from "./limits.ts";import { roomLeft } from "./room.ts";console.log("index.ts runs");console.log(`Room for ${roomLeft(3)} of ${taskLimit}`);
The common mistake: a type without type
print.ts already imports two names from tasks.ts, so when it
needs Task as well, the quickest edit is one more name in the
same list.
Common mistake
Importing a type in a plain import line
The top of print.ts, with Task added to the values:
print.tsts
import { alphabetical, percentFull, Task } from "./tasks.ts";
The check prints nothing, because tasks.ts does export Task.
Then node index.ts add "pay rent" does not even print the banner: Node
stops while it follows the import lines, before any line has run.
And node --test still ends with fail 0, because no test imports
print.ts.
SyntaxError: The requested module './tasks.ts' does not provide an export named 'Task'
The fix
Give the type a line of its own, with import type:
print.tsts
import type { Task } from "./tasks.ts";import { alphabetical, percentFull } from "./tasks.ts";
The message is the one lesson 5.11 showed for a function with no
export, but there the check had already stopped you, with TS2459.
So when the check passes and Node still says does not provide an export named, the name it gives is a type, imported without
type.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
These run in your browser, which cannot follow an import line, so
they ask about import lines rather than run them. Try any of them in
TaskKit for real.
Exercise · Read the code
Sort the names
index.ts needs four names from this tasks.ts: version,
Status, Task and sameTask. Which of them go in the
import type line?
tasks.tsts
export const version = "0.1";export type Status = "todo" | "done";export interface Task { readonly id: number; title: string; status: Status;}export function sameTask(newTask: string): (task: string) => boolean { return (task) => task.toLowerCase() === newTask.toLowerCase();}
Exercise · Fix the error
Fix the import lines
This program prints the import lines of an index.ts. Both lines
would stop Node. Fix them, so the program prints three lines
Node can run: the one from print.ts, one bringing in Task alone,
and one bringing in the two functions.
Loading the editor…
Exercise · Predict the result
Share the limit
Suppose TaskKit gets lesson 3.2's rule that a title is at most 40
characters, and the number goes into tasks.ts as
const titleLimit = 40;. index.ts wants to import it. What do you
write in tasks.ts in place of that line?
Exercise · Read the code
Answer the warning
A friend copies TaskKit's .ts files into a project of their own,
with its own package.json, and runs node index.ts add "pay rent".
TaskKit runs, but first Node prints a long warning whose first line
holds [MODULE_TYPELESS_PACKAGE_JSON] Warning:. What should they
do?
Recap
Recap · 3 questions
Check yourself
tasks.ts and print.ts each make const limit. Do they clash?
Check yourself
Why does from "./tasks" stop Node, though tasks.ts is there?
Check yourself
The check passes, but Node stops at import { Task }. Why?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
import and export: type module, .ts extensions, import type
What things are
Word
What it means
Module
A file that shares only what it exports
ES modules
The import and export way, the ECMAScript standard
CommonJS
Node's older way, with require
"type": "module"
Every file in this folder is an ES module
import type
A line of types only; Node strips it out
Code and commands
Write
To
export const …
Share a box
export interface Task
Share a type; export type too
import { capitalize }
Bring in a value, by its exact name
import type { Task }
Bring in a type
from "./tasks.ts"
This folder, the whole file name
npm pkg set type=module
Tell Node, once, how the files are written
Rules
Rule
What it means
Private by default
Only exported names leave a file
The whole name
Node never adds .ts to a path
Types apart
A type in a plain import stops Node
Values apart
A function in import type cannot be called: TS1361
Imports run first
Each file once, before the files that import it
Check the top file
TypeScript follows every import line
Where to go next
You can now split a program into modules that share boxes, functions
and types, and write import lines Node can follow: in an ES module
project, with the whole file name, and with types in import type.
TaskKit's program is four files now, each with one job.
Next is npm and package.json: installing packages and writing
scripts. There TaskKit's own code calls a package for the first
time, listed in the same package.json, and three short commands
replace the long check, test and run lines you type now.
Before you move on, take the .ts off "./command.ts" in
index.ts. Run the check, which passes, then node index.ts help,
and read the path in the error. Put the .ts back and run TaskKit
again.
Footnotes
devDependencies is the list --save-dev writes to
(lesson 1.4). The ^ in front of each version is explained in
the next lesson. ↩