# Using JavaScript Modules

Salesforce Certified JavaScript Developer I · lesson 10

Six rules cover every module question.

Video: https://www.youtube.com/watch?v=NIhZorC5r54
Page: https://shipitcertified.com/learn/salesforce-javascript-developer/using-javascript-modules/
Free slide PDF (free account): https://shipitcertified.com/learn/salesforce-javascript-developer/using-javascript-modules/

## Chapters

- 0:00 [Using JavaScript Modules](https://www.youtube.com/watch?v=NIhZorC5r54)
- 0:36 [Quick recap: four class rules](https://www.youtube.com/watch?v=NIhZorC5r54&t=36s)
- 1:08 [Six rules cover every module question](https://www.youtube.com/watch?v=NIhZorC5r54&t=68s)
- 1:55 [One table holds the whole lesson](https://www.youtube.com/watch?v=NIhZorC5r54&t=115s)
- 3:16 [Many named exports, but only one default](https://www.youtube.com/watch?v=NIhZorC5r54&t=196s)
- 4:20 [Import syntax mirrors the export form](https://www.youtube.com/watch?v=NIhZorC5r54&t=260s)
- 5:34 [Braces mean named; no braces means default](https://www.youtube.com/watch?v=NIhZorC5r54&t=334s)
- 6:21 [as renames; a namespace import collects everything](https://www.youtube.com/watch?v=NIhZorC5r54&t=381s)
- 7:41 [A re-export forwards without creating a local name](https://www.youtube.com/watch?v=NIhZorC5r54&t=461s)
- 8:48 [Imports are live bindings, not copies](https://www.youtube.com/watch?v=NIhZorC5r54&t=528s)
- 9:51 [Reading follows the exporter; writing is blocked](https://www.youtube.com/watch?v=NIhZorC5r54&t=591s)
- 10:41 [In a browser, a module script needs type="module"](https://www.youtube.com/watch?v=NIhZorC5r54&t=641s)
- 11:36 [import() loads on demand and returns a promise](https://www.youtube.com/watch?v=NIhZorC5r54&t=696s)
- 12:40 [Top-level await, and the errors modules throw](https://www.youtube.com/watch?v=NIhZorC5r54&t=760s)
- 13:27 [Node picks ESM or CommonJS from the file](https://www.youtube.com/watch?v=NIhZorC5r54&t=807s)
- 14:31 [ESM has no require, __dirname, or __filename](https://www.youtube.com/watch?v=NIhZorC5r54&t=871s)
- 15:24 [In LWC, every JavaScript file is an ES module](https://www.youtube.com/watch?v=NIhZorC5r54&t=924s)
- 16:13 [Six terms to say in your own words](https://www.youtube.com/watch?v=NIhZorC5r54&t=973s)
- 16:55 [Split it in two, predict, then run as .mjs](https://www.youtube.com/watch?v=NIhZorC5r54&t=1015s)
- 18:17 [Eight questions, closed book](https://www.youtube.com/watch?v=NIhZorC5r54&t=1097s)
- 19:19 [What does main.js log?](https://www.youtube.com/watch?v=NIhZorC5r54&t=1159s)
- 19:55 [2](https://www.youtube.com/watch?v=NIhZorC5r54&t=1195s)
- 20:43 [Four rules to carry into the exam](https://www.youtube.com/watch?v=NIhZorC5r54&t=1243s)
- 21:24 [Now test it, then move to scope and execution flow](https://www.youtube.com/watch?v=NIhZorC5r54&t=1284s)

## Transcript

### Using JavaScript Modules (0:00)

Welcome to module two, lesson four: using JavaScript modules. This module is called Objects, Functions, and Classes, and it carries twenty five percent of the exam. In this lesson we look at how code is split across files. An export shares a value, an import brings it in, and a dynamic import loads it on demand. The exam asks how they connect. By the end, you will be able to read a module, predict what an import sees, and pick the right syntax in the browser, in Node, and in a Lightning web component.

### Quick recap: four class rules (0:36)

Before we start, a quick recap from lesson three. First, a class cannot be used before its declaration, because of the temporal dead zone. Second, a derived constructor must call "super" before it touches "this". Third, private members, the ones that start with a hash, are not reachable outside the class body. And fourth, "instance of" walks the prototype chain. Today we move from classes to files: how code is split into modules and shared between them.

### Six rules cover every module question (1:08)

Here is what you will learn. This domain is twenty five percent of the exam, which works out to about fifteen questions. This lesson boils down to six rules. Modules run in three places: the browser, Node, and Lightning web components. First, named and default exports. Second, import syntax and renaming. Third, re-exports. Fourth, live, read-only bindings. Fifth, dynamic "import". And sixth, Node E S M versus Common J S. Live bindings and the default versus named syntax produce most of the questions, so we slow down there. We will also cover the module script type in browsers, top-level await, and modules in L W C.

### One table holds the whole lesson (1:55)

This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one row of this table, with an example, so pause here and read each row aloud. Export. The rule is many named exports, but only one default. The trap is that two defaults is a Syntax Error. The safe habit is to use the default for the main thing a module offers. Import. The rule is curly braces for a named import, and none for a default. The trap is putting braces around a default. The safe habit is to match the export form. Binding. The rule is that an import is live, but read-only. The trap is an importer that assigns to it. The safe habit is to call a function the exporter provides. Dynamic import. The rule is that it returns a promise. The trap is forgetting that the default export sits under the key default. The safe habit is to await it, or use "dot then". Node. The rule is that a dot M J S file, or a package type of module, makes E S M. The trap is that there is no "double underscore dir name" and no "require". The safe habit is to use "import dot meta dot dir name". One practical rule ties them together: read the export line first, then write the import to match it.

### Many named exports, but only one default (3:16)

Our first rule is about exports. Look at the code, a file called "math dot J S". The first line exports a constant, P I, as a named export. Next, the function "add" is also a named export, declared with the export keyword in front. Then comes the default export: export default function square. A module may have only one of these. Instead of putting the keyword on each declaration, a single export statement, with curly braces, can list the names together. So named exports are found by name, and the default export has no fixed name for the importer. Named exports are declared with the export keyword, or listed inside curly braces. A default export is allowed once per module, and the importer picks the name. Exports must be top level, never inside a function. And duplicate names, or two defaults, are a Syntax Error, so the module never runs. The exam point: a module can have many named exports, but only one default export.

### Import syntax mirrors the export form (4:20)

Rule two: import syntax mirrors the export form. Look at the code. The first line is a named import. Curly braces, the names P I and "add", then from, then the path. The names must match the exports exactly. The second line is a default import. No braces, and any local name you like. Here it is called S Q, but it could be anything. The third line combines both. The default name comes first, then curly braces for the named imports. The fourth line combines a default with a namespace import, which collects every export into one object. The last line is a side effect import. It runs the module and brings in no values. So the import always mirrors the export. A named import uses curly braces, then from, then the specifier, which is the path of the module. A default import has no braces, and any local name. You can combine a default with named imports or a namespace, and a side effect import runs the module without importing anything. The exam point: default imports have no braces; named imports need braces and the exported name.

### Braces mean named; no braces means default (5:34)

Here is the first trap. The wrong shortcut says: always wrap an import in curly braces. The correct exam test asks one question: was it exported with default? Then no braces, and any name. Look at the code. The module exports a default function called square. Importing it as square, with no braces, works. Importing it as S Q works too, because the importer picks the name for a default. But curly braces around square is wrong, because the module has no named export called square, and the import fails. A named import must use the exact exported name, unless you rename it with "as". The practical rule: check how the module exported the value, then copy that form.

### as renames; a namespace import collects everything (6:21)

Rule two continues with renaming, and with the namespace import. Look at the code. The first line renames on import. Add "as" sum means the local name is sum. Renaming also works on export: export add as plus publishes the function under the name plus. Next, a namespace import. Import star as m collects every export into one object called m. Then "m dot add" of one and two gives three, and "m dot P I" gives three point one four one five nine. The default export sits under the key default, so "m dot default" of three gives nine. The last line is the long form of a default import: default as S Q, inside curly braces. So "as" renames on import or on export. Import star as m makes every export a property of m. The default export sits under the key "default". And the namespace object is sealed: it has no prototype and cannot be changed, and there is no import star from without the "as". And the long form, "default as x" in curly braces, is just another way to write a default import. The exam point: a namespace import needs the "as", and the default export is "n s dot default".

### A re-export forwards without creating a local name (7:41)

Rule three: a re-export forwards another module's exports without creating a local name. Look at the code, an index file. The first line forwards one name from math, add. The second forwards it under a new name, plus. The third forwards a whole namespace, as math. The fourth line, export star from math, forwards all the named exports. The comment on the next line is the important part: named exports only. So how do you forward the default? The next line does it, export, curly braces, default, from math. And the last one forwards it under a new name, Square. In short, export curly braces from forwards one name, and export star as from forwards a namespace. And export star from forwards the named exports, but not the default. Re-exported names do not exist in that file's own code. This is how an index file gathers several modules into one entry point. The exam point: export star does not re-export the default. Use export, curly braces, default, from.

### Imports are live bindings, not copies (8:48)

Rule four: imports are live bindings, not copies. Look at the code. In the first file, count is exported with let, starting at zero. The function inc adds one to count. In main, we import count and inc, and call inc. Then we log count. It prints one, not zero, because the import follows the exporter's variable. The last line, assigning count equals five, is commented out, because it would throw a Type Error. The importer cannot reassign an import. So when the exporter updates count, every importer sees the new value. Live means linked to the original variable, not a snapshot taken at import time. The importer cannot reassign. Assigning gives a Type Error: Assignment to constant variable. But the properties of an imported object can still be changed. And import declarations are hoisted, so their side effects run first. The exam point: an importer sees the exporter's updates, but cannot reassign the binding.

### Reading follows the exporter; writing is blocked (9:51)

Here is the live binding trap. The wrong shortcut says: an import is a copy of the value at import time. The correct exam test asks: can the exporter change it? Then the importer sees the change. Look at the code. The exporter has a let called count, and a constant object called config. Say the exporter changes count by calling inc. Logging count shows the new value, not zero. But assigning count equals five is a Type Error, because the importer cannot reassign. Changing config dot debug to true is allowed, because it changes a property of the object, not the binding itself. So reassigning the binding fails, while mutating an object property does not. The practical rule: to change shared state, call a function the exporter provides.

### In a browser, a module script needs type="module" (10:41)

Now modules in the browser. A module script needs the attribute type equals module. Look at the code. The first script loads main dot J S as a module. The second is an inline module script, and it can import from math. The last script is a plain script, with no type module. If it uses import, that is an error. So import and export work only in modules. Module code is strict mode and module scoped, not global. Module scripts are deferred, and they run once, even if the page references them twice. Globals are still readable inside a module, but your own declarations do not leak out. One practical note: opening the page from the file system causes C O R S errors, so use a server that sends a JavaScript M I M E type. The exam point: import and export need type module, and top-level declarations are not global.

### import() loads on demand and returns a promise (11:36)

Rule five: a dynamic import loads on demand and returns a promise. Look at the code. In the function load, we destructure the result of awaiting import of math dot J S. The default export is the default property of the namespace object. Since default is a reserved word, we rename it to S Q, and take add by name. Then we log S Q of three and add of one and two, which prints nine and three. The second form uses "dot then". Import of math returns a promise, and the callback receives the namespace as m. So a dynamic import returns a promise of the namespace object, and you use await or "dot then". The default export is the default property, renamed when you destructure. It works from classic scripts too, and for conditional or runtime built specifiers. Prefer static imports when you do not need on-demand loading. The exam point: dynamic import is promise based, and the default export is "result dot default".

### Top-level await, and the errors modules throw (12:40)

This table covers top-level await, and the errors modules throw. Await at module top level. Parent modules wait for it, while sibling modules still load. An import in a plain script is a Syntax Error: cannot use import statement outside a module. A static import inside an if is also a Syntax Error, because imports must be at the top level. An unresolvable specifier is a Type Error. And cyclic imports give a Reference Error, but only if a variable is used before it is initialized. The practical rule: use dynamic import when the load must be conditional. The fix for a static import in the wrong place is type module, a dot M J S extension, or a dynamic import.

### Node picks ESM or CommonJS from the file (13:27)

Rule six: Node picks E S M or Common J S from the file. Four markers decide. The extension. A dot M J S file is E S M, and a dot C J S file is Common J S. The package dot json type. A type of module makes E S M, and a type of commonjs makes Common J S. The flag. The input type flag, set to module or commonjs, does the same for code given on the command line. And the syntax. E S M uses import and export. Common J S uses require and "module dot exports". Look at the code. Importing a Common J S file from E S M works, and its "module dot exports" becomes the default export. Relative specifiers need the extension, so the import of app must say dot J S. With no marker at all, Node inspects the source for E S module syntax. The exam point: dot M J S or type module makes E S M. Dot C J S or type commonjs makes Common J S.

### ESM has no require, __dirname, or __filename (14:31)

Here is the Node trap. The wrong shortcut says: Node globals work the same in every file. The correct exam test says: in E S M, use "import dot meta dot dir name" and "create require". Look at the code, a dot M J S file. Logging "double underscore dir name" is an error, because it is not defined in E S M. Instead, log "import dot meta dot dir name", and "import dot meta dot file name". And if you really need require, import "create require" from node colon module, and call it with "import dot meta dot U R L". Missing in E S M: require, exports, "module dot exports", and the double underscore file name and dir name. The exam point: require can load an ES module only if it has no top-level await.

### In LWC, every JavaScript file is an ES module (15:24)

Modules also run in Lightning web components. Every JavaScript file there is an E S module. Look at the code. In utils, we export the function "format". In my card, we import Lightning Element from lwc, and "format" from "c slash utils". The c is the namespace, and utils is the folder of the shared module. Finally, the class is the default export. A UI component imports Lightning Element from lwc. Its default export must be a class that extends it. To share code, you create a module and export what you want to share. And there is one default export, and the importer picks the name. Named exports use their names. The exam point: the component's default export is a class that extends Lightning Element.

### Six terms to say in your own words (16:13)

Here are six terms to say in your own words. Pause the video and try it. A named export is an export identified by name, and there can be many per module. A default export is the single export the importer names itself. A namespace import, import star as ns, gives all the exports on one object. A re-export, export from, forwards another module's exports. A live binding is an import that follows the exporter, and is read-only. And a dynamic import, import with parentheses, returns a promise of the namespace. Cover each card and explain the term aloud.

### Split it in two, predict, then run as .mjs (16:55)

This is the proof lab. Split a script into two modules, and watch a live binding change after import. Create two files. The first, "counter dot M J S", exports a let called count, plus two functions. The function inc adds one to count, and reset sets it back to zero. The second, "main dot M J S", imports count, inc, and reset. It logs count, calls inc twice, logs again, calls reset, logs a third time, and finally assigns count equals five. Pause the video and predict each output on paper first. Then run it with node on main dot M J S. Here are five predictions to check against your paper. Prediction one, the first log. It prints zero, because count starts at zero. Prediction two, the log after two calls to inc. It prints two, because the binding is live. Prediction three, the log after reset. It is back to zero. Prediction four, the assignment, count equals five. It throws a Type Error: Assignment to constant variable. Prediction five, the same file saved with a dot J S extension and no type. Node treats it as Common J S, so the import fails. A wrong prediction is the lesson. Go back to the slide that explains it.

### Eight questions, closed book (18:17)

Here are eight questions, closed book. Answer out loud, then listen for the answer. One. How many default exports can a module have? Exactly one. Two. Does export star from a module forward its default? No. Star skips the default. Three. You import count, then assign count equals five. What happens? A Type Error. Four. What does a dynamic import return? A promise. Five. What does a browser script need before it can use import? The type module attribute. Six. Can you use "double underscore dir name" inside a dot M J S file? No, it is not defined. Seven. Which extension forces Common J S? Dot C J S. Eight. With import star as m, where is the default export? On "m dot default". How many did you get? Anything you missed, go back to the slide for that rule.

### What does main.js log? (19:19)

Time for the practice question. Read the code carefully. A file, counter dot J S, exports a let called count, set to zero, and a function inc that adds one to count. The file main dot J S imports count and inc from counter, calls inc twice, and then logs count. What does main dot J S log? Option A: zero. Option B: one. Option C: two. Option D: Type Error. Pause now. Decide what an importer sees before you hear the answer.

### 2 (19:55)

The answer is C, two. Look at the code. In counter, count starts at zero, and inc adds one to it. Here is why it ends at two. Each inc call increments count inside counter, and main calls inc twice. The live import reflects it. Now the wrong options. A says zero. That treats the import as a snapshot taken at import time. But imports are live, so the value follows the exporter. B says one. That miscounts the calls. The code calls inc twice, so count goes up twice. D says Type Error. Only assigning to the import throws. Reading it, and calling inc, are allowed. The takeaway: an import is a live, read-only view of the exporter's variable.

### Four rules to carry into the exam (20:43)

Let's consolidate, with four rules to carry into the exam. Exports. A module has many named exports, but only one default. Duplicates are a Syntax Error. Imports. Braces for named, none for default. And export star skips the default. Bindings. They are live and read-only. A dynamic import returns a promise, and the default is on its default property. Node. A dot M J S file, or a type of module, is E S M. And there is no double underscore dir name and no require in E S M. Remember: match the import to the export, and never assign to an import.

### Now test it, then move to scope and execution flow (21:24)

That completes lesson four. Now test it, then move on to variable scope and execution flow. The flow is: read it, predict it, test it. Your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Variable Scope and Execution Flow, we trace scope, hoisting, closures, and the order code runs. See you there.
