Sub topic 17
What the compiler and framework add
This chapter assumes you know the four web component standards covered earlier: custom elements, shadow DOM, templates and slots, and ES modules. It also assumes you have read how a component bundle is laid out. The goal here is to separate what the browser does from what LWC contributes, starting with the two parts LWC adds: a build-time compiler and a runtime engine.
Two layers on top of the browser
A browser cannot run an LWC bundle directly. The .html template is not valid JavaScript, and decorators such as @api are not part of the language. LWC closes that gap in two stages.
- The compiler runs at build time. It turns each template, stylesheet and class into plain JavaScript modules.
- The engine runs in the page. It supplies the
LightningElementbase class and the code that creates elements, renders them and updates them.
On the Salesforce platform both stages run for you. In the open-source project you wire them up yourself, usually with a bundler plugin.
What the compiler does
The compiler is a set of packages, including a template compiler, a script transformer and a CSS transformer. Together they do four jobs.
Templates become render functions
The template compiler parses your HTML and generates a JavaScript function that builds the virtual DOM for the component. Your {name} expression becomes a read of this.name inside that function. Event attributes such as onchange={handleChange} become listeners bound to the component instance.
This is why template expressions are restricted. You can reference a property or a getter, and you can read a dotted path such as {item.label}. You cannot write {count + 1} or call a function inside a template. The compiler checks this at build time and fails with an error instead of producing a broken page.
Decorators are removed
Browsers do not run @api, @track or @wire. The script transformer reads them and replaces them with registration metadata. The engine uses that metadata to learn which fields are public, which are tracked and which are wired to data. After compilation the decorator syntax is gone from the output.
Styles are scoped
Shadow DOM already isolates styles when the browser supports it natively. LWC can also run on its own emulation layer, called synthetic shadow. For that case, and for consistent behavior, the CSS transformer rewrites your selectors and the template compiler tags the generated elements so the two match. You write plain selectors such as p { color: teal; } and the compiler handles the scoping.
Module names are resolved
An import such as import HelloGreeting from 'c/helloGreeting' is not a URL. The c is a namespace and helloGreeting is a bundle folder. The compiler's resolver maps that specifier to the right files. The browser's own module system never sees the shorthand.
What the engine does
The engine is the code that ships to the browser. Its main parts:
LightningElement: the base class every component extends. It gives youthis.template,this.dispatchEvent, the lifecycle hooks and other members.- Reactivity: the engine observes the fields a template reads. When you reassign one of them, the engine schedules a re-render. It does not need to rebuild the whole page.
- Rendering and diffing: the engine runs the compiled render function, compares the result with the previous output and patches only the nodes that changed.
- Custom element wiring: the engine connects your class to the custom element and shadow root machinery the browser provides.
- Synthetic shadow: an optional polyfill-like layer that emulates shadow DOM behavior where native shadow DOM is not used.
Running it yourself with open-source LWC
The open-source project shows the pipeline without the platform hiding it. A bundler plugin runs the compiler, and createElement hands a compiled class to the engine.
// rollup.config.js
import lwc from '@lwc/rollup-plugin';
import replace from '@rollup/plugin-replace';
export default {
input: 'src/main.js',
output: { file: 'dist/main.js', format: 'esm' },
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
preventAssignment: true
}),
lwc({ rootDir: 'src/modules' })
]
};// src/main.js
import { createElement } from 'lwc';
import HelloGreeting from 'c/helloGreeting';
const element = createElement('c-hello-greeting', { is: HelloGreeting });
document.body.appendChild(element);Place the earlier helloGreeting.html and helloGreeting.js in src/modules/c/helloGreeting/. The rollup plugin compiles them, and createElement asks the engine to build the element. The browser then handles the rest as it would for any custom element.
Build-time versus runtime
Knowing which stage handles a feature helps you debug. A build error and a runtime error usually point to different causes.
| Feature | Handled at build time | Handled at runtime |
|---|---|---|
| Template syntax checks | Yes | No |
| Expression restrictions | Yes | No |
| Decorator processing | Yes, turned into metadata | Yes, metadata is read |
| Selector scoping | Yes, selectors rewritten | Yes, attributes applied |
| Re-render after a field change | No | Yes |
| Event dispatch and handling | No | Yes, uses browser events |
| Custom element registration | No | Yes |
Common errors
- Using a JavaScript expression in a template. Writing
{count + 1}fails to compile. Move the logic into a getter in the class and bind the getter. - Expecting a mutation to re-render. The engine reacts to reassignment of a field. For an object or array, replace it with a new value, as in
this.items = [...this.items, next]. Changing one nested property in place may not trigger the update. - Missing
keyin a loop. The compiler requires a uniquekeyon the first element insidefor:each. Without it the build fails. - Treating decorators as standard. Copying a component's class into plain browser code leaves
@apias a syntax error. The decorators only work when the compiler processes the file. - Wrong module path. An import from
c/helloGreetingfails if the folder and file names differ in case. Match them exactly.
What this means for the standards
Everything the compiler produces and the engine drives ends up as ordinary browser features: classes, custom elements, shadow roots, DOM events and ES modules. The compiler and engine are the parts that are specific to LWC. The next chapter lists which features belong to each side.
Exercise
A teammate writes <p>Total: {price * quantity}</p> in a template and the build fails. Explain why it fails, which layer reports the failure, and how to fix it.
Show answer
The template compiler, which runs at build time, only accepts property and getter references in expressions, not arithmetic. Because it runs at build time, the failure appears as a build error and not in the browser. Fix it by adding a getter to the class, such as get total() { return this.price * this.quantity; }, and changing the template to <p>Total: {total}</p>.
Exercise
In the open-source setup, which step does the browser's own module system perform, and which step does the LWC compiler's resolver perform, when main.js runs import HelloGreeting from 'c/helloGreeting'?
Show answer
The LWC resolver, used during bundling, maps the c/helloGreeting specifier to the files in src/modules/c/helloGreeting/. The browser's module system only loads the resulting bundled ES module. It never sees the c/ shorthand.