CodeBlanks Logo Icon CodeBlanks

export and import

Learn ES module export and import.

export and import

With the export keyword you can export a variable, function, or type from a module. From another module you import these items with import { name } from "./path". The names inside curly braces must match the exported names exactly.

// matematik.ts
export function topla(a: number, b: number) {
  return a + b;
}

// app.ts
import { topla } from "./matematik";
console.log(topla(2, 3));  // 5

Multiple named exports

A module can have as many named exports as you want. Each export keyword adds a new export. When importing, you can take multiple items in a single import statement separated by commas: import { topla, cikar } from "./matematik".

Practice Call an exported function

Define topla as an exported function with signature (a: number, b: number): number returning a + b. Then print the result of topla(3, 4) with console.log.

Starter code

index.ts
// topla adında bir fonksiyonu dışa aktararak tanımla
// a ve b parametreleri alsın, toplamlarını döndürsün
// fonksiyonu 3 ve 4 ile çağırıp sonucu yazdır

Sample solution

index.ts
export function topla(a: number, b: number): number {
  return a + b;
}
console.log(topla(3, 4));

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which syntax is used to import a named-exported function?

  • import { topla } from "./matematik" Correct answer
  • import topla from "./matematik"
  • import * topla from "./matematik"
  • import [ topla ] from "./matematik"

Explanation: For a named export you give the name in curly braces: import { topla } from "./matematik". Writing without braces is for default exports; * requires as; square brackets are invalid.

2 Add export

Question
____ function topla(a: number, b: number): number {
  return a + b;
}
Answer
export function topla(a: number, b: number): number {
  return a + b;
}

Explanation: To export a function you write export at the start of its declaration. default is for a separate default export; public and static are for class members, not module exports.

3 export and import parts

Term Meaning
export function topla Named export declaration
import { topla } Import with curly braces
{ topla, cikar } Multiple names with commas
from "./matematik" Module path

All lessons in Intermediate