Sub topic 5
ES modules as the unit of code sharing
This chapter assumes you know JavaScript functions, classes and variable scope. It also assumes you have seen import statements in a front-end project, and that you know a custom element is a class registered as an HTML tag. You don't need to know how a bundler works.
What an ES module is
An ES module is a JavaScript file that the language itself treats as a separate unit of code. It has its own scope, it declares what it shares with export, and it pulls in code from other files with import. ES modules are one of the four standards LWC builds on, alongside custom elements, shadow DOM and templates.
Three properties matter for the rest of this tutorial:
- Module scope. Top-level
let,const,functionandclassdeclarations belong to the module. They do not become globals unless you export them. - Strict mode. Module code always runs in strict mode, so you do not write
"use strict". - Single evaluation. The engine runs a module's top-level code once, however many files import it. Every importer receives the same bindings.
Exports and imports
A module can have any number of named exports and at most one default export.
// mathUtils.js
export const TAX_RATE = 0.2;
export function addTax(amount) {
return amount * (1 + TAX_RATE);
}
export default function round2(value) {
return Math.round(value * 100) / 100;
}An importer picks names from the module. Named imports must match the exported names and go inside braces. A default import can have any local name.
// pricing.js
import round2, { addTax, TAX_RATE as rate } from './mathUtils.js';
export function priceWithTax(amount) {
return round2(addTax(amount));
}
export const currentRate = rate;Imports are live, read-only bindings, not copies. If the exporting module changes an exported let variable, importers see the new value. Importers cannot assign to the binding.
| Form | Exporting side | Importing side |
|---|---|---|
| Named | `export const x = 1;` | `import { x } from './m.js';` |
| Renamed | `export { x as y };` | `import { y as z } from './m.js';` |
| Default | `export default class A {}` | `import A from './m.js';` |
| Namespace | none | `import * as m from './m.js';` |
How a browser loads a module graph
The browser handles import in three steps. It first fetches the entry file and parses it. Then it follows every import statement to build a graph of dependencies, fetching each file once. Last, it evaluates the modules in dependency order, so a module runs after everything it imports.
Because the engine reads import and export before running any code, it can do this without executing the files. The statements must sit at the top level of the file, and the path must be a string literal. That restriction is what makes static analysis possible. Tools can see the full dependency graph and remove unused exports without running the code.
In a plain page, you start the graph with a script tag that has type="module". Relative specifiers such as ./mathUtils.js need the full file extension, because the browser does not guess it.
<script type="module" src="./main.js"></script>Bare specifiers
A path that starts with ./, ../ or / is a relative or absolute URL. A name such as 'lwc' is a bare specifier, and the language does not define how to find it. Browsers reject bare specifiers unless an import map tells them where to look. In practice, a build tool or a platform loader resolves them.
LWC relies on this. The first line of most component classes is:
import { LightningElement } from 'lwc';'lwc' is not a file path. The LWC compiler and runtime resolve it to the framework module that exports LightningElement. This is standard module syntax with a framework-defined resolution step.
Modules in an LWC project
In LWC, every component's JavaScript file is an ES module. The component class is its default export, as you saw in the helloGreeting.js example earlier in this tutorial:
// helloGreeting.js
import { LightningElement } from 'lwc';
export default class HelloGreeting extends LightningElement {
name = 'World';
}You can also write modules that are not components. These are often called service modules or utility modules. Put them in a bundle folder under your component directory, and name the main file after the folder. A bundle pricing containing pricing.js can export named functions:
// pricing/pricing.js
export const TAX_RATE = 0.2;
export function addTax(amount) {
return Math.round(amount * (1 + TAX_RATE) * 100) / 100;
}Another component imports it by namespace and folder name. In a Salesforce project the default namespace is c.
// checkoutSummary/checkoutSummary.js
import { LightningElement, api } from 'lwc';
import { addTax } from 'c/pricing';
export default class CheckoutSummary extends LightningElement {
@api subtotal = 0;
get total() {
return addTax(this.subtotal);
}
}Here 'c/pricing' is a bare specifier that the LWC compiler resolves to the pricing bundle in the c namespace. You do not write a file extension or a relative path.
Platform-specific import specifiers
On the Salesforce platform, some bare specifiers do not point to JavaScript files in your project. The compiler turns them into generated code that provides the value.
| Specifier pattern | What it gives you |
|---|---|
| `lwc` | The framework API: `LightningElement`, `api`, `track`, `wire` |
| `c/name` | Another bundle in the same namespace |
| `@salesforce/apex/Class.method` | A function that calls an Apex method |
| `@salesforce/label/c.labelName` | The text of a custom label |
| `@salesforce/schema/Account.Name` | A reference to an object or field |
These specifiers use standard import syntax, but they are not portable. Outside the Salesforce platform, the open-source LWC project does not provide @salesforce/* modules, and the browser would reject them. Chapter content later in this tutorial separates standard features from LWC additions. Treat these specifiers as additions that reuse a standard mechanism.
Dynamic import
A static import must be at the top level. When you need to load code on demand, use the import() expression. It returns a promise that resolves to the module namespace object.
async function loadFormatter() {
const module = await import('./format.js');
return module.default;
}This is standard JavaScript. Whether import() is allowed for a specific specifier in LWC depends on the platform. Salesforce restricts it in some contexts, so check the platform documentation before relying on it.
Common errors and gotchas
- Missing braces.
import addTax from 'c/pricing'imports the default export. If the module has only named exports,addTaxisundefinedor the build fails. Useimport { addTax } from 'c/pricing'. - Named versus default confusion. A component class must be the default export. If you write
export class HelloGreeting, the platform cannot find the component. - Circular imports. If
a.jsimportsb.jsandb.jsimportsa.js, one of them runs before the other finishes. Reading an export at the top level can then fail with aReferenceErrorfor alet,constorclassbinding, or giveundefinedfor a hoistedvar. Move shared code to a third module. - Shared state. Because a module is evaluated once, a top-level variable is shared by every importer. That makes a module a simple singleton. It also means that state in a service module persists across components that use it.
- Mutating imports.
rate = 0.3on an imported binding throws aTypeError. Change state through an exported function.
Exercise
A service module c/counter has let count = 0; at the top level and exports export function next() { return ++count; }. Two different components each call next() once during their lifetime. What do the two calls return, and why?
Show answer
The first call returns 1 and the second returns 2 (in whichever order they run). The module is evaluated once, so both components import the same function bound to the same count variable. The variable is module scope, not component scope.
Exercise
A teammate writes import { LightningElement } from './lwc.js'; in a component and the build fails. What is the correct line, and what kind of specifier is it?
Show answer
import { LightningElement } from 'lwc';. The string 'lwc' is a bare specifier, which the LWC compiler and runtime resolve to the framework module. It is not a relative file path.