JS Tower
JavaScript & TypeScriptМодуль 6: ООП и паттерны

Модули

import и export в JavaScript

Цель урока

В этом уроке ты научишься:

  • Экспортировать функции и переменные
  • Импортировать модули
  • Использовать динамический импорт

Именованный экспорт

// math.js
export const PI = 3.14159;

export function square(n) {
  return n * n;
}

export function cube(n) {
  return n * n * n;
}

Импорт

// main.js
import { PI, square, cube } from "./math.js";

console.log(PI);        // 3.14159
console.log(square(5)); // 25

Переименование

import { square as sq, cube as cb } from "./math.js";

console.log(sq(5)); // 25

Импорт всего

import * as math from "./math.js";

console.log(math.PI);
console.log(math.square(5));

Экспорт по умолчанию

// user.js
export default class User {
  constructor(name) {
    this.name = name;
  }
}

Импорт

// main.js
import User from "./user.js";

let user = new User("Иван");

Одно имя

При импорте default можно использовать любое имя.


Комбинация

// api.js
export default function fetchData() {
  // ...
}

export const API_URL = "https://api.example.com";
export const TIMEOUT = 5000;
// main.js
import fetchData, { API_URL, TIMEOUT } from "./api.js";

Реэкспорт

// index.js
export { User } from "./user.js";
export { Product } from "./product.js";
export { Order } from "./order.js";

// Или всё сразу
export * from "./utils.js";
// main.js
import { User, Product, Order } from "./index.js";

Динамический импорт

async function loadModule() {
  let module = await import("./heavy-module.js");
  module.doSomething();
}

// Или с then
import("./module.js")
  .then(module => {
    module.default();
  });

Условный импорт

let modulePath = isAdmin ? "./admin.js" : "./user.js";
let module = await import(modulePath);

Структура проекта

src/
  components/
    Button.js
    Input.js
    index.js      // реэкспорт
  utils/
    format.js
    validate.js
    index.js      // реэкспорт
  main.js
// components/index.js
export { Button } from "./Button.js";
export { Input } from "./Input.js";

// main.js
import { Button, Input } from "./components";

Практика

Задание 1: Именованный экспорт

Задача: Создай модуль с функциями.

Запустите код для проверки
Loading...
Ваш вывод:
Ожидаемый результат:
8
15

Задание 2: Экспорт по умолчанию

Задача: Создай класс и экспортируй по умолчанию.

Запустите код для проверки
Loading...
Ваш вывод:
Ожидаемый результат:
[LOG] Сообщение

Проверь себя

  1. Чем именованный экспорт отличается от default?
  2. Как импортировать всё из модуля?
  3. Когда использовать динамический импорт?