ES modullar
JavaScript faylları bir-birindən necə asılı olur: import və export formaları, modul scope-u, statik quruluş və tree shaking, canlı binding-lər, icra ardıcıllığı və dövrlər, dinamik import və top-level await, CommonJS ilə uyğunluq, bundler-lər və Vite.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
İlkin şərt yoxdur.
Bu mövzu Junior səviyyəsindən başlayır.
ES modulu nədir
ES modulu nəyə ehtiyacı olduğunu import ilə, nə təqdim etdiyini isə export ilə elan edən JavaScript faylıdır. Modullar standartlaşdırılmazdan əvvəl (ES2015) bütün <script>-lər bir qlobal bölüşürdü: hər üst səviyyəli var və funksiya qlobala çevrilirdi, script teqlərinin ardıcıllığını isə əllə idarə etmək lazım gəlirdi. Modullar bu problemləri həll edir:
- Öz scope-u. Modulun üst səviyyəli dəyişənləri yalnız ona aiddir. Sən özün qoymasan,
window-a heç nə düşmür. - Həmişə strict mode.
"use strict"yazmağa ehtiyac yoxdur, üst səviyyədəthisisəundefined-dir. - Bir dəfə icra olunur. Modulu neçə fayl import etsə də, onun kodu bir dəfə işləyir və bütün import edənlər həmin bir nüsxəni bölüşür.
- Açıq asılılıqlar. Hər fayl nədən istifadə etdiyini adbaad göstərir, ona görə də brauzerlər və alətlər kodu işə salmadan asılılıq qrafını qura bilir.
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}// main.js
import { area } from "./math.js";
console.log(area(2)); // 12.56636Brauzerdə
<script type="module" src="/main.js"></script>- Modul script-ləri default olaraq təxirə salınır (deferred): HTML parse olunarkən paralel yüklənir və parse bitəndən sonra sənəddəki ardıcıllıqla icra olunur.
asyncatributu ilə modul özü və import etdikləri yüklənən kimi, heç bir ardıcıllıq gözləmədən işləyir. - Modullar CORS ilə yüklənir. Ona görə də
index.html-ifile://ilə açanda heç nə işləmir; lokal server işlət. Servertext/javascriptkimi JavaScript MIME tipi göndərməlidir. - Bir neçə
<script>teqi və ya import eyni modula istinad etsə də, o, yalnız bir dəfə icra olunur.
Node.js-də
Fayl .mjs ilə bitirsə və ya .js ilə bitib ən yaxın package.json-da "type": "module" yazılıbsa, ES modulu sayılır. .cjs faylları həmişə CommonJS-dir. "type" sahəsi olmayanda Node.js (22.7 və 20.19-dan bəri) .js faylında import/export sintaksisini özü də aşkar edir, amma sənədləri bu sahəni açıq yazmağı tövsiyə edir, çünki aşkarlamanın performans xərci var. İki sistemin müqayisəsi senior bölmələrindədir.
An ES module is a JavaScript file that declares what it needs with import and what it offers with export. Before modules were standardized (ES2015), every <script> shared one global : each top-level var and function became a global, and the order of script tags had to be managed by hand. Modules fix this:
- Own scope. Top-level variables of a module are local to it. Nothing reaches
windowunless you put it there. - Strict mode, always. No
"use strict"is needed, and top-levelthisisundefined. - Evaluated once. However many files import a module, its code runs once, and every importer shares that one instance.
- Explicit dependencies. Each file names what it uses, so browsers and tools can build the dependency graph without running code.
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}// main.js
import { area } from "./math.js";
console.log(area(2)); // 12.56636In the browser
<script type="module" src="/main.js"></script>- Module scripts are deferred by default: they download in parallel with HTML parsing and run after parsing, in document order. With
async, a module runs as soon as it and its imports have loaded, in no particular order. - Modules are fetched with CORS. Opening
index.htmlfromfile://therefore fails; use a local server. The server must send a JavaScript MIME type such astext/javascript. - A module that several
<script>tags or imports refer to still runs only once.
In Node.js
A file is an ES module if it ends in .mjs, or ends in .js and the nearest package.json has "type": "module". .cjs files are always CommonJS. Without a "type" field, Node.js (since 22.7 and 20.19) also detects import/export syntax in a .js file, but its docs recommend setting the field explicitly, because detection has a performance cost. The senior sections compare the two systems.
import və export formaları
// user.js
export const ROLES = ["admin", "editor"];
export function formatName(user) {
return user.first + " " + user.last;
}
export default class User {}// app.js
import User, { ROLES, formatName as fullName } from "./user.js";
import * as users from "./user.js";
import "./polyfills.js";Adlı export-lar
export const, export function, export class və ya siyahı: export { a, b as c }. Import edən fiqurlu mötərizədə dəqiq adı yazır və onu as ilə dəyişə bilər. Səhv yazılmış ad heç bir kod işə düşməmiş xəta verir, məsələn: SyntaxError: The requested module './user.js' does not provide an export named 'formatNme'.
Default export
Hər modulda ən çoxu bir dənə: export default expression. Import edən istədiyi adı seçir (yuxarıda User). Birləşmiş forma: import User, { ROLES } from "./user.js".
Namespace import
import * as users bütün export-ları xassə kimi saxlayan bir obyekt verir: users.ROLES, users.formatName, default export isə users.default kimi. Bu obyekt yalnız oxumaq üçündür.
Yan effekt üçün import
import "./polyfills.js" heç bir ad import etmədən modulu icra edir. Bundler ilə yığılan tətbiqlərdə polyfill-lər və qlobal CSS üçün tipikdir.
Yenidən export
// index.js
export { formatName } from "./user.js";
export { default as User } from "./user.js";
export * from "./dates.js";
export * as validators from "./validators.js";export * bütün adlı export-ları yenidən export edir, default export-u isə yox. Yalnız belə yenidən export-lardan ibarət fayla barrel deyilir.
Adlı, yoxsa default?
Bir çox komanda adlı export-lara üstünlük verir: kodun hər yerində eyni ad, daha yaxşı autocomplete və adı dəyişmə, link mərhələsində tutulan yazı səhvləri. Default export-lar alətin onu gözlədiyi yerlərdə geniş yayılıb: React.lazy default-u komponent olan modul gözləyir, bəzi framework-lər isə hər route faylından default export istəyir.
Specifier-lər
Brauzerdə nisbi specifier-də ./ və ya ../ və fayl uzantısı olmalıdır: "./user" user.js-ə çevrilmir. "react" kimi bare specifier-ə isə import map və ya bundler lazımdır (senior bölmələrinə bax).
// user.js
export const ROLES = ["admin", "editor"];
export function formatName(user) {
return user.first + " " + user.last;
}
export default class User {}// app.js
import User, { ROLES, formatName as fullName } from "./user.js";
import * as users from "./user.js";
import "./polyfills.js";Named exports
export const, export function, export class or a list: export { a, b as c }. The importer uses the exact name in braces and may rename it with as. A misspelled name fails before any code runs, with an error such as SyntaxError: The requested module './user.js' does not provide an export named 'formatNme'.
Default export
At most one per module: export default expression. The importer chooses any name (User above). Combined form: import User, { ROLES } from "./user.js".
Namespace import
import * as users gives one object with every export as a property: users.ROLES, users.formatName, and the default export as users.default. The object is read-only.
Side-effect import
import "./polyfills.js" runs the module without importing any name. Typical for polyfills and global CSS in bundled apps.
Re-exports
// index.js
export { formatName } from "./user.js";
export { default as User } from "./user.js";
export * from "./dates.js";
export * as validators from "./validators.js";export * re-exports all named exports, but not the default export. A file made only of such re-exports is called a barrel.
Named or default?
Many teams prefer named exports: the same name everywhere in the codebase, better autocomplete and renaming, and typos caught at link time. Default exports remain common where a tool expects them: React.lazy expects a module whose default is a component, and some frameworks expect a default export per route file.
Specifiers
In browsers, a relative specifier needs ./ or ../ and the file extension: "./user" is not resolved to user.js. A bare specifier such as "react" needs an import map or a bundler (see the senior sections).
Statik quruluş və tree shaking
import və export elanları statikdir:
- onlar yalnız modulun üst səviyyəsində yazıla bilər,
ifbloklarında və ya funksiyaların içində yox; - specifier hesablanan dəyər yox, həmişə string literal olur;
- import-lar hoisting olunur: modulun öz kodundan hər hansı biri işləməzdən əvvəl onun asılılıqları yüklənir və bir-birinə bağlanır (link).
Buna görə də modul qrafı bütövlükdə icradan əvvəl məlum olur. Qrafın yüklənməsi üç mərhələdən keçir:
- Qurma (construction): hər modulu yüklə və parse et, onun import elanlarını oxu və bunu hər asılılıq üçün təkrarla.
- Bağlama (linking): hər export üçün binding yarat və hər import-u adını çəkdiyi export-a bağla. Mövcud olmayan export burada, hələ heç bir kod işləməmiş xəta verir.
- İcra (evaluation): modulların gövdələrini işə sal, əvvəlcə asılılıqları.
Tree shaking
Bundler (Rollup, Rolldown, webpack, esbuild) hansı export-ların istifadə olunduğunu statik olaraq gördüyü üçün heç kimin import etmədiyi export-ları ata bilər:
// format.js
export function formatPrice(value) {
return value.toFixed(2) + " AZN";
}
export function formatHugeReport(rows) {
return rows.map((row) => row.join(";")).join("\n");
}// cart.js
import { formatPrice } from "./format.js";formatHugeReport-u başqa heç nə import etmirsə, production bundle-da o olmayacaq.
Buna nə mane olur
- Üst səviyyədə yan effektlər. İcra olunanda nəsə edən modul (prototipi dəyişən, qlobal qeydiyyat aparan, storage-ə yazan) heç bir export-u işlədilməsə də saxlanmalıdır.
package.json-dakı"sideEffects"sahəsi (webpack-in təqdim etdiyi və bundler-lərin çoxunun oxuduğu sahə) onlara hansı faylları atmağın təhlükəsiz olduğunu deyir: heç biri üçünfalse, ya da["*.css"]kimi siyahı. - CommonJS.
require()adi funksiya çağırışıdır,module.exportsisə icra zamanı qurulan obyekt. Ona görə bundler ümumi halda xassənin işlədilmədiyini sübut edə bilmir. - Namespace-ə dinamik müraciət.
utils.formatPriceanaliz oluna bilir;utils[name]isə bundler-i bütün export-ları saxlamağa məcbur edir. - Gizli effekti olan kod.
const theme = createTheme()kimi üst səviyyəli çağırış, bundler onun təmiz (pure) olduğunu sübut edə bilmirsə, saxlanılır; bəzi bundler-lər çağırışın qarşısında/* @__PURE__ */annotasiyasını qəbul edir.
Barrel faylları production build-də tree shaking-ə mane olmur, amma development server-ləri və test runner-ləri barrel-in arxasındakı hər modulu yükləməyə məcbur edir, həm də dövri import yaratmağı asanlaşdırır.
import and export declarations are static:
- they are allowed only at the top level of a module, not inside
ifblocks or functions; - the specifier is a string literal, never a computed value;
- imports are hoisted: a module's dependencies are loaded and linked before any of its own code runs.
Because of this, the whole module graph is known before execution. Loading a graph has three phases:
- Construction: fetch and parse each module, read its import declarations, and repeat for every dependency.
- Linking: create the bindings for every export and connect each import to the export it names. A missing export fails here, before any code has run.
- Evaluation: run the module bodies, dependencies first.
Tree shaking
Since a bundler (Rollup, Rolldown, webpack, esbuild) can see statically which exports are used, it can drop the ones nobody imports:
// format.js
export function formatPrice(value) {
return value.toFixed(2) + " AZN";
}
export function formatHugeReport(rows) {
return rows.map((row) => row.join(";")).join("\n");
}// cart.js
import { formatPrice } from "./format.js";If nothing else imports formatHugeReport, the production bundle does not contain it.
What prevents it
- Top-level side effects. A module that does something when evaluated (patches a prototype, registers a global, writes to storage) must be kept even if no export is used. The
"sideEffects"field inpackage.json, introduced by webpack and read by most bundlers, tells them which files are safe to drop:falsefor none, or a list such as["*.css"]. - CommonJS.
require()is an ordinary function call andmodule.exportsan object built at runtime, so a bundler cannot generally prove that a property is unused. - Dynamic access to a namespace.
utils.formatPriceis analysable;utils[name]forces the bundler to keep every export. - Code with hidden effects. A top-level call such as
const theme = createTheme()is kept unless the bundler can prove it is pure; some bundlers accept a/* @__PURE__ */annotation in front of the call.
Barrel files are not a problem for tree shaking in production builds, but they make development servers and test runners load every module behind the barrel, and they make circular imports easier to create.
Canlı binding-lər: import surət yox, baxışdır
Import olunan ad export olunan dəyərin surəti deyil. O, export edən modulun dəyişəninə canlı, yalnız oxunan baxışdır.
// counter.js
export let count = 0;
export function increment() {
count += 1;
}// main.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1main.js count-a heç vaxt dəyər mənimsətməyib, amma 1 görür: hər iki ad counter.js-dəki eyni binding-ə istinad edir.
Import edən üçün yalnız oxumaq
main.js-də count = 5 yazmaq icra zamanı TypeError: Assignment to constant variable. atır. Dəyişənlərinə yalnız export edən modulun özü dəyər verə bilər; onları kənardan dəyişmək üçün increment kimi funksiya export et. Export olunan obyektin xassələrini isə istənilən import edən dəyişə bilər (settings.debug = true). Bu, bütün tətbiq üçün ortaq dəyişkən state-dir, ona görə bunu düşünərək et.
Default export xüsusi haldır
export default expression ifadəni bir dəfə hesablayır və həmin dəyəri export edir. export { value as default } isə binding-i export edir. Export edən modul sonradan value-ya yeni dəyər versə, dəyişikliyi yalnız ikinci forma göstərir (MDN də məhz bu fərqi təsvir edir).
Bu niyə vacibdir
- Dövrlər. Modul işə başlayanda hələ inisializasiya olunmamış binding sonradan etibarlı ola bilər. Canlı binding-lər olmasaydı, dövri import-lar həmişəlik
undefinedgörərdi. - CommonJS ilə müqayisə.
const { count } = require("./counter")çağırış anındakı dəyəri kopyalayır; sonrakı dəyişikliklər görünmür. - Bundler-lər bunu təkrarlamalıdır. webpack import-ları canlı saxlamaq üçün hər export-u modulun exports obyektində getter kimi təyin edir, ona görə də hər oxuma cari dəyəri qaytarır. Rollup və Rolldown isə scope hoisting işlədir: modullar bir scope-da birləşdirilir və import eyni dəyişənə birbaşa istinada çevrilir.
Namespace obyekti də (import * as counter) canlıdır: counter.count həmişə cari dəyəri oxuyur.
An imported name is not a copy of the exported value. It is a live, read-only view of the exporting module's variable.
// counter.js
export let count = 0;
export function increment() {
count += 1;
}// main.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1main.js never assigned count, yet it sees 1: both names refer to the same binding in counter.js.
Read-only for importers
Writing count = 5 in main.js throws TypeError: Assignment to constant variable. at runtime. Only the exporting module can assign its variables; to change them from outside, export a function such as increment. Properties of an exported object can still be changed by any importer (settings.debug = true), which is shared mutable state across the whole app, so do it deliberately.
The default export is a special case
export default expression evaluates the expression once and exports that value. export { value as default } exports the binding. If the exporter later reassigns value, only the second form shows the change (MDN describes exactly this difference).
Why it matters
- Cycles. A binding that is not initialized yet when a module starts can become valid later. Without live bindings, circular imports would see
undefinedforever. - Comparison with CommonJS.
const { count } = require("./counter")copies the value at the moment of the call; later changes are invisible. - Bundlers must reproduce it. webpack keeps imports live by defining each export as a getter on the module's exports object, so every read returns the current value. Rollup and Rolldown use scope hoisting instead: modules are concatenated into one scope, so an import becomes a direct reference to the same variable.
A namespace object (import * as counter) is live as well: counter.count always reads the current value.
İcra ardıcıllığı və dövri import-lar
İcra dərinliyə doğru gedir: modulun gövdəsi işləməzdən əvvəl onun import etdiyi bütün modullar import elanlarının yazıldığı ardıcıllıqla icra olunur. Artıq icra olunmuş modul ötürülür, ona görə də ortaq asılılıq bir dəfə, ona ehtiyacı olan ilk moduldan əvvəl işləyir. Giriş (entry) modulu ən sonda işləyir.
Import ardıcıllığının əhəmiyyəti buradan gəlir: main.js əvvəlcə ./polyfills.js-i, sonra ./app.js-i import edirsə, polyfill-lər app.js-in hər hansı kodundan əvvəl işləyəcək. Amma buna arxalanmaq kövrəkdir; modul ehtiyac duyduğunu özü import etməlidir.
Dövri import-lar
a.js b.js-i, b.js isə a.js-i import edirsə, ikisi də birinci işləyə bilməz. Qrafa a.js-dən daxil olanda yükləyici əvvəlcə b.js-i icra etməyə başlayır. Onun a.js import-u artıq icra prosesində olan modula yönəlir, ona görə də b.js a.js hələ işləmədən icra olunur:
// a.js
import { b } from "./b.js";
export const a = "a";
console.log("a sees " + b);// b.js
import { a } from "./a.js";
export const b = "b";
console.log("b sees " + a);a.js-i işə salanda b.js-dən ReferenceError: Cannot access 'a' before initialization atılır. a binding-i artıq mövcuddur (link zamanı yaradılıb), amma onun const elanı hələ icra olunmayıb, yəni o hələ . var ilə bunun əvəzinə undefined alardın, bu da eyni bug-ın daha səssiz variantıdır.
Dövrün içində nə işləyir
- Funksiya elanları link zamanı inisializasiya olunur, ona görə də
b.jsa.js-in export etdiyi funksiyanı üst səviyyədə çağıra bilər, bir şərtlə ki, həmin funksiyaa.js-in hələ inisializasiya olunmamışlet/constdəyişənlərini oxumasın. - Import-ları sonra oxumaq, yəni bütün qraf icra olunandan sonra çağırılan funksiyaların içində oxumaq işləyir, çünki canlı binding-lər o vaxt artıq inisializasiya olunmuş dəyərlərə yönəlir.
Dövrləri necə düzəltmək və qarşısını almaq olar
- Ortaq kodu hər ikisinin import etdiyi üçüncü modula köçür.
- Import-ları modulun üst səviyyəsində yox, funksiyaların içində oxu.
- Barrel fayllarına diqqət et:
"../components"-dən import edən komponent (həmin qovluğunindex.js-i də elə bu komponenti yenidən export edirsə) barrel vasitəsilə dövr yaradır. - Dövrləri avtomatik aşkarla, məsələn,
eslint-plugin-import-unimport/no-cycleqaydası və yamadge --circularilə.
Evaluation goes depth-first: before a module's body runs, all the modules it imports are evaluated, in the order its import declarations appear. A module that was already evaluated is skipped, so a shared dependency runs once, before the first module that needs it. The entry module runs last.
This is why import order can matter: if main.js imports ./polyfills.js first and ./app.js second, the polyfills run before any code of app.js. Relying on that is fragile, though; a module should import what it needs itself.
Circular imports
If a.js imports b.js and b.js imports a.js, both cannot run first. When the graph is entered at a.js, the loader starts evaluating b.js first. Its import of a.js points to a module that is already in progress, so b.js runs while a.js has not run yet:
// a.js
import { b } from "./b.js";
export const a = "a";
console.log("a sees " + b);// b.js
import { a } from "./a.js";
export const b = "b";
console.log("b sees " + a);Running a.js throws ReferenceError: Cannot access 'a' before initialization from b.js. The binding a already exists (it was created during linking), but its const declaration has not executed, so it is still in the . With var you would get undefined instead, which is a quieter version of the same bug.
What works inside a cycle
- Function declarations are initialized during linking, so
b.jsmay call a function exported bya.jsat its top level, as long as that function does not reada.js's uninitializedlet/constvariables. - Reading imports later, inside functions that run after the whole graph has been evaluated, works because live bindings then point to initialized values.
How to fix and prevent cycles
- Move the shared code into a third module that both import.
- Read imports inside functions rather than at module top level.
- Watch barrel files: a component that imports from
"../components"(whoseindex.jsre-exports that same component) creates a cycle through the barrel. - Detect cycles automatically, for example with the
import/no-cyclerule ofeslint-plugin-importor withmadge --circular.
Dinamik import() və top-level await
import()
import(specifier) elan yox, ifadədir. O, istənilən yerdə yazıla bilər (funksiyalarda, if bloklarında, hətta klassik script-lərdə), specifier-i hesablana bilər və modulun namespace obyektinə promise qaytarır:
button.addEventListener("click", async () => {
const { openEditor } = await import("./editor.js");
openEditor();
});Artıq yüklənmiş modul yenidən icra olunmur: import() hər dəfə eyni namespace obyekti ilə resolve olunur.
Code splitting
Bundler-lər hər import()-u bölünmə nöqtəsi sayır: editor.js və yalnız onun işlətdiyi asılılıqlar ayrıca chunk-a düşür və brauzer onu kod ilk dəfə işləyəndə yükləyir. Statik import-lar kodu ilkin bundle-da saxlayır, dinamik import-lar isə onu oradan çıxarır.
const Settings = lazy(() => import("./Settings.jsx"));React.lazy-yə default-u komponent olan obyektlə resolve olunan promise lazımdır. Adlı export üçün onu çevir: lazy(() => import("./Chart.jsx").then((m) => ({ default: m.Chart }))).
Bundler yalnız analiz edə bildiyini bölə bilər. Tam dinamik import(url) icra zamanı brauzerin öhdəsinə qalır; Vite və webpack isə import(`./locales/${lang}.js`) kimi qovluğu və uzantısı sabit olan şablonu qəbul edir və uyğun gələn hər fayl üçün bir chunk yaradır.
Top-level await
Modulda await üst səviyyədə də yazıla bilər:
// config.js
const response = await fetch("/config.json");
export const config = await response.json();Modul asinxron olur: onu birbaşa və ya başqa modullar vasitəsilə import edən hər modul öz gövdəsini işə salmazdan əvvəl onun bitməsini gözləyir. Ondan asılı olmayan modullar isə bu müddətdə icra olunmağa davam edir (MDN: qonşu modulları bloklamır).
Nəticələri:
- Giriş zəncirindəki yavaş top-level
awaitbütün tətbiqin başlamasını gecikdirir. Başlamaq üçün lazım olmayan məlumat üçün bunun əvəzinə promise və ya yükləyici funksiya export et. - O, rədd edilsə, modul icra oluna bilmir, onu import edənlər də uğursuz olur və həmin modulun sonrakı hər import-u eyni xətanı alır.
- Bu, yalnız ES modullarında işləyir: Chrome 89+, Firefox 89+, Node.js 14.8+. Safari onu Safari 15 ilə əlavə edib, amma MDN Safari 27 çıxana qədər dəstəyi qismən sayır: bir neçə modulun top-level
await-li eyni modulu eyni anda import etməsi düzgün işləmir. İçində top-levelawaitolan qrafın CommonJSrequire()ilə yüklənməsiERR_REQUIRE_ASYNC_MODULEatır.
import()
import(specifier) is an expression, not a declaration. It can appear anywhere (in functions, in if blocks, even in classic scripts), its specifier may be computed, and it returns a promise for the module namespace object:
button.addEventListener("click", async () => {
const { openEditor } = await import("./editor.js");
openEditor();
});A module that is already loaded is not evaluated again: import() resolves to the same namespace object every time.
Code splitting
Bundlers treat every import() as a split point: editor.js and the dependencies only it uses go into a separate chunk, which the browser downloads the first time the code runs. Static imports keep code in the initial bundle; dynamic ones move it out.
const Settings = lazy(() => import("./Settings.jsx"));React.lazy needs a promise that resolves to an object whose default is a component. For a named export, map it: lazy(() => import("./Chart.jsx").then((m) => ({ default: m.Chart }))).
A bundler can split only what it can analyse. A fully dynamic import(url) is left to the browser at runtime; Vite and webpack accept a template with a fixed folder and extension, such as import(`./locales/${lang}.js`), and create one chunk per matching file.
Top-level await
In a module, await may appear at the top level:
// config.js
const response = await fetch("/config.json");
export const config = await response.json();The module becomes asynchronous: every module that imports it, directly or through other modules, waits until it has finished before its own body runs. Modules that do not depend on it keep evaluating in the meantime (MDN: it does not block sibling modules).
Consequences:
- A slow top-level
awaitin the entry chain delays the start of the whole app. For data that is not needed to start, export a promise or a loader function instead. - If it rejects, the module fails to evaluate, its importers fail too, and every later import of that module receives the same error.
- It is available only in ES modules: Chrome 89+, Firefox 89+, Node.js 14.8+. Safari added it in Safari 15, but MDN counts support as partial until Safari 27: several modules importing the same module with top-level
awaitat once is not handled. A CommonJSrequire()of a graph that contains top-levelawaitthrowsERR_REQUIRE_ASYNC_MODULE.
Node.js-də ES modullar və CommonJS
CommonJS (require, module.exports) ES modullarından çox-çox əvvəl Node.js-in modul sistemi idi və npm-in böyük hissəsi onunla yazılıb. İki sistem təkcə sintaksisə görə fərqlənmir:
| CommonJS | ES modullar | |
|---|---|---|
| Yüklənmə | sinxron, require() işləyəndə | əvvəlcə qraf parse olunur və bağlanır, sonra icra olunur (asinxron da ola bilər) |
| Import olunan dəyərlər | module.exports obyektindən oxunur; destructuring kopyalayır | canlı binding-lər |
Top-level await | yoxdur | var |
| Cari faylın yolu | __filename, __dirname | import.meta.filename, import.meta.dirname |
| Fayl tipləri | .cjs və ya "type": "commonjs" ilə .js | .mjs və ya "type": "module" ilə .js |
ES modulundan CommonJS-i import etmək
import legacy from "./legacy.cjs" default export kimi module.exports-u verir. import { parse } from "./legacy.cjs" kimi adlı import-lar Node.js mənbə kodunun statik analizi ilə onları aşkar edə bildikdə işləyir. Bu aşkarlama "bacardığı qədər" işləyən evristikadır və belə adlı import-lar canlı deyil.
ES modullarının require() ilə yüklənməsi
require() Node.js 20.19, 22.12 və 23.0-dan bəri ES modullarını bayraqsız yükləyə bilir, Node.js 25.4 isə bu imkanın eksperimental statusunu götürüb. O, modulun namespace obyektini qaytarır:
const { formatDate } = require("./dates.mjs");
const Logger = require("./logger.mjs").default;Modul "module.exports" string adı ilə dəyər export edərək require()-ın nə qaytaracağını özü seçə bilər: export { Logger as "module.exports" }. Yeganə sərt məhdudiyyət: yüklənən qraf sinxron olmalıdır. İçindəki hər hansı modul top-level await işlədirsə, Node.js ERR_REQUIRE_ASYNC_MODULE atır; orada import() işlət.
Bu, CommonJS koduna yalnız ESM olan paketlərdən istifadə etməyə imkan verir. Əvvəllər məhz bu ehtiyac kitabxana müəlliflərini iki build buraxmağa məcbur edirdi.
Dual package hazard
Həm CommonJS, həm də ESM build-i olan paket bir tətbiqdə iki dəfə yüklənə bilər: bir dəfə require, bir dəfə də import vasitəsilə. Bu, iki modul nüsxəsi deməkdir: iki cache, singleton state-in iki surəti və onların arasında uğursuz olan instanceof yoxlamaları. Hansı yükləyicinin hansı faylı alacağını paketin exports sahəsi müəyyən edir:
{
"name": "date-kit",
"type": "module",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
}
}State-i təkrarlanan fayllardan kənarda saxla və ya yalnız ESM buraxıb CommonJS istifadəçilərinə require(esm) vasitəsilə xidmət et.
CommonJS (require, module.exports) was Node.js's module system long before ES modules existed, and most of npm was written in it. The two systems differ in more than syntax:
| CommonJS | ES modules | |
|---|---|---|
| Loading | synchronous, when require() runs | graph parsed and linked first, then evaluated (possibly asynchronously) |
| Imported values | read from the module.exports object; destructuring copies | live bindings |
Top-level await | no | yes |
| Paths of the current file | __filename, __dirname | import.meta.filename, import.meta.dirname |
| File types | .cjs, or .js with "type": "commonjs" | .mjs, or .js with "type": "module" |
Importing CommonJS from ES modules
import legacy from "./legacy.cjs" gives module.exports as the default export. Named imports such as import { parse } from "./legacy.cjs" work when Node.js's static analysis of the source can detect them. The detection is a best-effort heuristic, and such named imports are not live.
require() of ES modules
require() can load ES modules without a flag since Node.js 20.19, 22.12 and 23.0, and Node.js 25.4 removed the feature's experimental status. It returns the module namespace object:
const { formatDate } = require("./dates.mjs");
const Logger = require("./logger.mjs").default;A module can choose what require() returns by exporting a value under the string name "module.exports": export { Logger as "module.exports" }. The one hard limit: the required graph must be synchronous. If any module in it uses top-level await, Node.js throws ERR_REQUIRE_ASYNC_MODULE; use import() there.
This lets CommonJS code use ESM-only packages, which used to push library authors into shipping two builds.
The dual package hazard
A package that ships both a CommonJS and an ESM build can end up loaded twice in one app: once through require, once through import. That means two module instances: two caches, two copies of singleton state, and instanceof checks failing between them. The package's exports field decides which file each loader receives:
{
"name": "date-kit",
"type": "module",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
}
}Keep state outside the duplicated files, or ship only ESM and let require(esm) serve CommonJS consumers.
Bare specifier-lər, bundler-lər və Vite dev server
Brauzerlər yalnız URL-ləri resolve edir: "./utils.js", "/src/app.js", "https://…". "react" kimi bare specifier nəsə onu URL-ə çevirməsə, xəta verir.
Import map-lər
<script type="importmap">
{
"imports": {
"react": "/vendor/react.js"
}
}
</script>
<script type="module" src="/main.js"></script>Import map-lər mart 2023-dən bütün əsas brauzerlərdə var (Baseline, geniş əlçatandır). Map ona arxalanan modul script-lərindən əvvəl gəlməlidir. Onlar build-siz layihələri praktik edir, amma sorğu şəlaləsini (waterfall) aradan qaldırmır: hər iç-içə import yalnız onun valideyni yüklənib parse olunandan sonra aşkar edilir. <link rel="modulepreload"> məlum modulları əvvəlcədən elan etməyə imkan verir.
Bundler nə edir
Bundler hər faylı parse edib onun import-larını tapır, onları izləyərək modul qrafı qurur, hər modulu funksiyaya çevirir və bu funksiyaları asılılıq ardıcıllığı ilə çağıran kiçik runtime əlavə edir. Platformadakı Mini Bundler build layihəsində belə bundler-i özün yazırsan: acorn ilə import-ların tapılmasından dövrlərin idarə olunmasına qədər. Klassik bundler-in nəticəsi sadələşdirilmiş şəkildə belə görünür:
const modules = {
"./math.js": (exports) => {
exports.area = (radius) => 3.14159 * radius * radius;
},
"./main.js": (exports, require) => {
const { area } = require("./math.js");
console.log(area(2));
},
};
const cache = {};
function require(id) {
if (cache[id]) return cache[id];
const exports = (cache[id] = {});
modules[id](exports, require);
return exports;
}
require("./main.js");Cache sayəsində hər modul, onu neçə modul require etməsindən asılı olmayaraq, bir dəfə işləyir. Real bundler-lər bunun üzərinə tree shaking, scope hoisting, hər import() üçün chunk və minification əlavə edir.
Development rejimində Vite
Vite development zamanı sənin mənbə kodunu bundle etmir. Brauzer /src/main.jsx-i native modul kimi yükləyir və hər import dev server-ə sorğuya çevrilir. Server həmin bir faylı tələb olunan anda öz plugin pipeline-ı ilə çevirir (JSX, TypeScript). Import analizi bare import-ları real URL-lərə çevirir, məsələn, /node_modules/.vite/deps/react.js?v=…. Asılılıqlar bir dəfə Rolldown ilə əvvəlcədən bundle olunur (Vite 8): CommonJS paketləri ESM-ə çevrilir, yüzlərlə daxili modulu olan paket isə (lodash-es-də 600-dən çox var) bir sorğuya çevrilir. HMR də eyni native modullar üzərində işləyir: redaktədən sonra brauzer dəyişən modulu yenidən import edir, import.meta.hot.accept() çağırmış kod isə onu səhifəni yeniləmədən yerində əvəz edir.
Platformadakı "Vite: from request to module" turu (vite v8.3.8) bu yolu transform middleware, plugin container, import analizi və HMR vasitəsilə izləyir. Production üçün vite build yenə də bundle edir, çünki çoxlu kiçik iç-içə sorğu bir neçə optimallaşdırılmış chunk-dan yavaşdır.
Browsers resolve only URLs: "./utils.js", "/src/app.js", "https://…". A bare specifier such as "react" is an error, unless something maps it to a URL.
Import maps
<script type="importmap">
{
"imports": {
"react": "/vendor/react.js"
}
}
</script>
<script type="module" src="/main.js"></script>Import maps have been available in all major browsers since March 2023 (Baseline widely available). The map must come before the module scripts that rely on it. They make no-build setups practical, but they do not remove the request waterfall: each nested import is discovered only after its parent has been downloaded and parsed. <link rel="modulepreload"> lets you announce known modules early.
What a bundler does
A bundler parses every file to find its imports, follows them into a module graph, rewrites each module into a function and adds a small runtime that calls those functions in dependency order. The platform's Mini Bundler build project lets you write one yourself, from parsing imports with acorn to handling cycles. The output of a classic bundler, simplified, has this shape:
const modules = {
"./math.js": (exports) => {
exports.area = (radius) => 3.14159 * radius * radius;
},
"./main.js": (exports, require) => {
const { area } = require("./math.js");
console.log(area(2));
},
};
const cache = {};
function require(id) {
if (cache[id]) return cache[id];
const exports = (cache[id] = {});
modules[id](exports, require);
return exports;
}
require("./main.js");Because of the cache, every module runs once, however many modules require it. Real bundlers add tree shaking, scope hoisting, chunks at every import() and minification.
Vite in development
Vite does not bundle your source code in development. The browser loads /src/main.jsx as a native module, and each import becomes a request to the dev server, which transforms that one file on demand (JSX, TypeScript) through its plugin pipeline. Import analysis rewrites bare imports to real URLs, such as /node_modules/.vite/deps/react.js?v=…. Dependencies are pre-bundled once with Rolldown (Vite 8): CommonJS packages become ESM, and a package with hundreds of internal modules (lodash-es has over 600) becomes one request. HMR runs over the same native modules: after an edit the browser imports the changed module again, and code that called import.meta.hot.accept() swaps it in place without a page reload.
The platform's tour "Vite: from request to module" (vite v8.3.8) follows this path through the transform middleware, the plugin container, import analysis and HMR. For production, vite build still bundles, because many small nested requests are slower than a few optimized chunks.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "ES modullar öz scope-u olan, asılılıqlarını import ilə, API-sini isə export ilə elan edən fayllardır. Quruluş statikdir, ona görə də bütün qraf hər hansı kod işləməmiş məlum olur: alətlər tree shaking edə bilir, yükləyici isə hər import-u öz export-una bağlayır. Import-lar canlı, yalnız oxunan binding-lərdir, hər modul bir dəfə icra olunur, import() isə kodu lazım olanda yükləyir."
Gözlənilən suallar
- Adlı, yoxsa default export? Nəyə üstünlük verdiyini və səbəbini de (sabit adlar, refactoring), default export-un harada gözlənildiyini də qeyd et (
React.lazy, route faylları). - Tree shaking nədir və nə vaxt işləmir? Statik import-lar işlədilməyən export-ları görünən edir. Üst səviyyədəki yan effektlər, CommonJS və namespace-ə dinamik müraciət ona mane olur;
"sideEffects"bundler-ə nəyi ata biləcəyini deyir. - Canlı binding nədir? Sayğac nümunəsini göstər, sonra yalnız oxumaq qaydasının
TypeError-unu, sonra daexport default valueiləexport { value as default }arasındakı fərqi. - Başlanğıcda "Cannot access 'x' before initialization" alırıq. Dövri import modulu onun asılılığının
constelanları icra olunmazdan əvvəl işə salıb. İcra ardıcıllığını və dövrü necə qırmaq olacağını izah et. - Code splitting necə işləyir? Hər
import()bölünmə nöqtəsidir; chunk kod işləyəndə yüklənir. - ESM və CommonJS. Yüklənmə modeli, canlı binding-lər, top-level
await, hər iki istiqamətdə uyğunluq,require(esm)vəERR_REQUIRE_ASYNC_MODULE.
Bal itirdən səhvlər
- Import-un dəyəri kopyaladığını demək. Bu, canlı binding-dir; kopyalayan yalnız CommonJS-dəki destructuring-dir.
- Modulların hər import-da yenidən icra olunduğunu demək. Hər modul nüsxəsi bir dəfə icra olunur, sonrakı import-lar onu təkrar istifadə edir.
type="module"script-lərinin parse-ı blokladığını demək. Onlar default olaraq təxirə salınır.import()-u sinxron adlandırmaq. O, promise qaytarır.
Senior səviyyəni göstərən məqamlar
Dil qaydalarını alətlərlə bağla: bundler qrafı necə qurur və modulları necə yenidən yazır, Vite niyə development-də native ESM verir, production-da isə bundle edir, top-level await tətbiqin başlamasını necə dəyişir və böyük kod bazasında import dövrünü necə tapıb qırardın.
A 30-second answer. "ES modules are files with their own scope that declare dependencies with import and their API with export. The structure is static, so the whole graph is known before any code runs: tools can tree-shake it, and the loader links every import to its export. Imports are live read-only bindings, each module is evaluated once, and import() loads code on demand."
Questions you are likely to get
- Named or default export? Say what you prefer and why (stable names, refactoring), and where a default export is expected (
React.lazy, route files). - What is tree shaking and when does it fail? Static imports make unused exports visible. It fails with side effects at top level, CommonJS and dynamic namespace access;
"sideEffects"tells the bundler what it may drop. - What is a live binding? Show the counter example, then the read-only
TypeError, then the difference betweenexport default valueandexport { value as default }. - We get "Cannot access 'x' before initialization" at startup. A circular import evaluated a module before its dependency's
constdeclarations ran. Explain the evaluation order and how to break the cycle. - How does code splitting work? Each
import()is a split point; the chunk is fetched when the code runs. - ESM vs CommonJS. Loading model, live bindings, top-level
await, interop in both directions,require(esm)andERR_REQUIRE_ASYNC_MODULE.
Mistakes that cost points
- Saying an import copies the value. It is a live binding; only CommonJS destructuring copies.
- Saying modules are evaluated each time they are imported. Once per module instance; later imports reuse it.
- Saying
type="module"scripts block parsing. They are deferred by default. - Calling
import()synchronous. It returns a promise.
Senior signal
Connect the language rules to the tools: how a bundler builds the graph and rewrites modules, why Vite serves native ESM in development but bundles for production, how top-level await changes startup, and how you would find and break an import cycle in a large codebase.
ES modullarını review edərkən nəyi yoxlamalı
Bu siyahını yazmadığın kodu review edəndə işlət: komanda yoldaşının pull request-i, kitabxananın issue tracker-indəki snippet və ya AI assistentin təklifi. Bircə ehtiyatsız import tətbiqi başlanğıcda çökdürə, ilkin bundle-ı lazımsız yerə böyüdə və ya tree shaking-ə (işlədilməyən export-ların atılmasına) mane ola bilər.
- Yeni import dövri import-a səbəb olurmu? İki fayl bir-birini, hətta barrel
index.jsvasitəsilə import edirsə, onlardan biri digərininconstelanlarından əvvəl işə düşür vəReferenceError: Cannot access 'a' before initializationatır.madge --circularvə yaimport/no-cyclelint qaydasını işə sal. - Modul üst səviyyədə iş görürmü? Prototipi dəyişən, qlobal qeydiyyat aparan və ya storage-ə yazan kod import zamanı işləyir və heç nə işlədilməsə də bundle-da qalır. Export olunan funksiyaya üstünlük ver; kitabxanadırsa,
package.json-dakı"sideEffects"sahəsini yoxla. - İlk ekrana lazım olmayan kod statik import olunurmu? Yalnız klikdən sonra lazım olan kodu
import()ilə yüklə ki, ayrıca chunk-a düşsün;React.lazyüçün isədefaultexport komponent olmalıdır. - Başlanğıc zəncirində top-level
awaitvarmı? Ondan asılı olan hər modul onu gözləyir, o rədd edilsə, uğursuz olur. Başlanğıcda lazım olmayan data üçün promise və ya yükləyici funksiya export et. - Import edən modul import olunan ada və ya export olunan obyektə yazırmı?
count = 5TypeErroratır, çünki import-lar yalnız oxunan canlı binding-lərdir; export olunan obyekti dəyişmək isə bütün tətbiq üçün ortaq state yaradır.incrementkimi funksiya export etməyə üstünlük ver. - Specifier-lər kodun işlədiyi yerdə resolve olunacaqmı? Brauzerdə nisbi yolda
./və uzantı olmalıdır,"react"kimi bare adlara isə import map və ya bundler lazımdır. Node.js-də.mjsuzantısını və ya"type": "module"sahəsini yoxla.
Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. One careless import can crash the app at startup, bloat the initial bundle or defeat tree shaking (dropping unused exports).
- Does a new import close a cycle? If two files import each other, even through a barrel
index.js, one runs before the other'sconstdeclarations have run and throwsReferenceError: Cannot access 'a' before initialization. Runmadge --circularor theimport/no-cyclelint rule. - Does the module do work at the top level? Code that patches a prototype, registers a global or writes to storage runs on import and stays in the bundle even if nothing is used. Prefer an exported function; in a library, check
"sideEffects"inpackage.json. - Is code that the first screen does not need imported statically? Load code used only after a click with
import(), which puts it in a separate chunk; forReact.lazy, thedefaultexport must be a component. - Is there a top-level
awaiton the startup path? Every module that depends on it waits, and fails if it rejects. For data not needed at start, export a promise or a loader function. - Does an importer write to an imported name or an exported object?
count = 5throws aTypeError, since imports are read-only live bindings, and mutating an exported object creates app-wide shared state. Prefer exporting a function such asincrement. - Will the specifiers resolve where the code runs? Browsers need
./and the extension in relative paths, and an import map or a bundler for bare names like"react". In Node.js, check.mjsor"type": "module".
Özünü yoxla
Təcrübədə sına
Bu mövzudan istifadə edən praktiki işlər.
Özün qur
Real kodda gör
Buna əsaslanan real kitabxanaların mənbə kodu üzrə bələdçili turlar.