Sub topic 4
Importing: Named, Default, Namespace, and Renamed Imports
This chapter assumes you know core JavaScript syntax, including object destructuring, and that you have read the earlier chapters on named and default exports. Here you will learn each form an import declaration can take, how to combine forms, and the errors that come from mixing them up. How the module path is resolved is covered in the next chapter. Live bindings get a chapter of their own.
The Shape of an Import Declaration
An import declaration has two parts. The import clause says which bindings to create. The module specifier is the string after from and says where the module is.
import { area } from './math.js';
// ^^^^^^^^ ^^^^^^^^^^^
// import clause module specifierThe engine reads every import declaration before it runs any of your code, which puts three rules on the syntax:
- Import declarations may appear only at the top level of a module. You cannot put one inside a function, an
ifblock, or atryblock. - The specifier must be a plain string literal. Template literals and variables are not allowed.
- Imports are hoisted. The bindings exist before the first line of the module runs, wherever the declaration appears in the file.
If you need to choose a module at runtime, use dynamic import(), which a later chapter covers.
Named Imports
A named import asks for an export by its exported name. The braces look like destructuring, but the rules are different.
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}
function circumference(radius) {
return 2 * PI * radius;
}
export { circumference as perimeter };// main.js
import { PI, area, perimeter } from './math.js';
console.log(PI); // 3.14159
console.log(area(2)); // 12.56636
console.log(perimeter(1)); // 6.28318The name you write must match the exported name exactly. math.js exports perimeter, so import { circumference } fails, even though the function inside the file is called circumference.
Renaming with `as`
Use as to give an imported binding a different local name. This prevents collisions when two modules export the same name, and it lets you pick a name that reads better in your own code.
import { area as circleArea } from './math.js';
import { area as squareArea } from './square.js';
console.log(circleArea(2), squareArea(2));Once you rename, only the new name exists in your module. Writing area here would throw a ReferenceError.
How Named Imports Differ from Destructuring
| Feature | Object destructuring | Named import |
|---|---|---|
| Rename syntax | `{ area: circleArea }` | `{ area as circleArea }` |
| Default values | `{ area = fallback }` allowed | Not allowed |
| Nested patterns | Allowed | Not allowed |
| Missing name | Gives `undefined` | `SyntaxError` before any code runs |
| Result | A new variable holding a copy of the value | A read-only binding to the exporter's variable |
The missing-name row matters most. Destructuring a property that does not exist quietly gives you undefined. A named import of an export that does not exist stops the whole module graph during linking, so none of its code runs. In Chrome and Node.js the message looks like this:
SyntaxError: The requested module './math.js' does not provide an export named 'circumference'Default Imports
A default import has no braces. You choose any local name, because the default export has no name the importer has to match.
// logger.js
export default function log(message) {
console.log(`[app] ${message}`);
}
export const level = 'info';// main.js
import writeLog from './logger.js';
writeLog('started'); // [app] startedThe engine treats a default export as a named export called default, so these two lines do the same thing:
import writeLog from './logger.js';
import { default as writeLog } from './logger.js';You must rename the long form, because default is a reserved word and cannot be a variable name. import { default } from './logger.js' is a syntax error.
Namespace Imports
A namespace import collects every export of a module into one object:
import * as math from './math.js';
console.log(math.PI); // 3.14159
console.log(math.area(3)); // 28.27431
console.log(math.perimeter); // [Function: circumference]The namespace object is not an ordinary object:
- It is sealed and its properties are read-only.
math.PI = 3throws aTypeErrorin a module, because modules always run in strict mode. - It has a
nullprototype, so methods such ashasOwnPropertyare missing from it. - Its keys are the exported names in alphabetical order. A default export shows up as the key
default. Object.prototype.toString.call(math)returns"[object Module]".
Unlike a named import, reading an export that does not exist from a namespace does not fail at link time. math.circumference is simply undefined. Namespace imports are useful when a module exports many related functions, or when the prefix makes the code clearer, such as math.area compared with a bare area.
Combining Forms
One declaration can hold a default import together with either named imports or a namespace import. The default import must come first.
import log, { level } from './logger.js';
import log2, * as loggerNs from './logger.js';
log(`level=${level}`); // [app] level=info
console.log(loggerNs.default === log2); // trueThe grammar does not allow named and namespace imports in the same declaration. import * as ns, { level } from ... is invalid, so write two declarations instead. Importing the same module twice is cheap: the module is loaded and evaluated once, and both declarations share that one instance.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Braces around a default export: `import { log } from './logger.js'` | `SyntaxError: ... does not provide an export named 'log'` | `import log from './logger.js'` |
| No braces for a named export: `import level from './logger.js'` | Error that no export named `default` exists, or the wrong value if a default happens to exist | `import { level } from './logger.js'` |
| Destructuring rename: `import { area: a } from ...` | `SyntaxError` | `import { area as a } from ...` |
| Import inside a function or block | `SyntaxError: Cannot use import statement` or an unexpected token error | Move it to the top level, or use `import()` |
| Assigning to an imported binding | `TypeError: Assignment to constant variable` | Copy it into a local variable, or call a setter that the exporting module provides |
Exercise
logger.js has export default function log() {} and export const level = 'info';. Which of these declarations are valid, and which fail? (1) import { default as l, level } from './logger.js'; (2) import * as ns, { level } from './logger.js'; (3) import l, * as ns from './logger.js'; (4) import { log } from './logger.js';
Show answer
(1) is valid. It renames the default export to l and imports level. (2) is a syntax error, because a namespace import cannot be combined with named imports. (3) is valid: a default import followed by a namespace import. (4) fails at link time with a SyntaxError, because the function's local name log is not an export name. Only default is exported for it.
Exercise
math.js does not export circumference. Why does import { circumference } from './math.js' stop the program before any code runs, while import * as math from './math.js'; console.log(math.circumference); prints undefined?
Show answer
Named imports are checked against the exporting module's export list during linking, before evaluation, so a missing name is a SyntaxError. A namespace import only binds the namespace object. Reading a missing property from that object at runtime gives undefined, just as it does on any object.
Exercise
Write one import declaration that brings in logger.js's default export as writeLog and its level export as logLevel.
Show answer
import writeLog, { level as logLevel } from './logger.js';