Sub topic 10
Helper JavaScript modules
This chapter assumes you know ES modules (import and export), the basic bundle layout, and how a component's JavaScript class connects to its template. Here you will see how to add extra .js files to a bundle, how to share code between components, and which mistakes to avoid.
What a helper module is
A helper module is a JavaScript file in a bundle folder that is not the component's main class file. The main file has the same base name as the folder, such as greetingCard.js. Any other .js file in the folder is a plain ES module. It has no template, no LightningElement base class, and no markup tag.
Helper modules hold logic that does not belong in the component class:
- Pure functions for formatting, parsing, or validating data.
- Constants such as limits, labels, and event names.
- Shared data-mapping code that several methods in one component use.
Moving this code out keeps the class focused on state and event handling. It also makes the code easy to test, because a pure function can be tested without creating a component.
Adding a helper to a bundle
Place the helper next to the other files in the bundle. The helper's name is up to you, but it must not match the folder name. That name belongs to the component's main class file.
force-app/main/default/lwc/
└── greetingCard/
├── greetingCard.html
├── greetingCard.js
├── greetingCard.js-meta.xml
├── greetingFormatter.js
└── __tests__/
├── greetingCard.test.js
└── greetingFormatter.test.jsThe helper exports what other code needs. Named exports are the usual choice because they make imports explicit and let tools find unused code.
// greetingFormatter.js
export const MAX_NAME_LENGTH = 30;
export function formatName(rawName) {
const trimmed = (rawName || '').trim().slice(0, MAX_NAME_LENGTH);
if (!trimmed) {
return 'World';
}
return trimmed.charAt(0).toUpperCase() + trimmed.slice(1);
}The component class imports the helper with a relative path. The .js extension is optional.
// greetingCard.js
import { LightningElement, api } from 'lwc';
import { formatName } from './greetingFormatter';
export default class GreetingCard extends LightningElement {
_name = 'World';
@api
get name() {
return this._name;
}
set name(value) {
this._name = formatName(value);
}
}The template does not change. It still reads {name} from the class.
<template>
<lightning-card title="Greeting">
<p class="greeting">Hello, {name}!</p>
</lightning-card>
</template>If a parent sets name to " ada ", the setter stores "Ada" and the card shows Hello, Ada!.
What the template can and cannot see
A template can reach only the properties, getters, and methods of its own class. It cannot call a function imported from a helper module.
<!-- This does not work: formatName is not a class member -->
<p>{formatName(name)}</p>To use a helper's result in the template, call the helper from a getter and bind the getter.
import { LightningElement, api } from 'lwc';
import { formatName } from './greetingFormatter';
export default class GreetingCard extends LightningElement {
@api name;
get displayName() {
return formatName(this.name);
}
}<p>{displayName}</p>Template expressions are limited to property lookups. Computing values in the class keeps the template simple and keeps the logic testable.
Sharing code across components
A relative import such as ./greetingFormatter reaches only files in the same bundle. A different component cannot import it, and c/greetingCard resolves only to the main file of that bundle, not to its helpers.
To share code, put it in a service component. This is a bundle whose main JavaScript file exports functions instead of a component class. It has no HTML file. Other components import it by module name, using the c namespace followed by the folder name in camelCase.
force-app/main/default/lwc/
└── textUtils/
├── textUtils.js
└── textUtils.js-meta.xml// textUtils.js
export function truncate(text, max) {
if (typeof text !== 'string' || text.length <= max) {
return text;
}
return text.slice(0, max - 1) + '…';
}
export function slugify(text) {
return String(text)
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}The service component still needs a configuration file to deploy. It does not need to be exposed in App Builder, so set isExposed to false.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>Any component can now import from it.
import { LightningElement, api } from 'lwc';
import { truncate } from 'c/textUtils';
export default class ArticleSummary extends LightningElement {
@api body = '';
get preview() {
return truncate(this.body, 120);
}
}Choosing between the two approaches
| Question | Helper in the same bundle | Service component |
|---|---|---|
| Who can import it? | Only the main file and other files in that bundle | Any component in the project or namespace |
| Import path | `./greetingFormatter` | `c/textUtils` |
| Needs `js-meta.xml`? | No, the bundle already has one | Yes, it is its own bundle |
| Best for | Logic tied to one component | Logic used by two or more components |
Start with a helper in the bundle. Promote it to a service component when a second component needs the same code. Promoting it early adds a deployable bundle that you must keep stable for every consumer.
Edge cases and gotchas
Module state is shared
The platform evaluates a module once, and every importer shares that one instance. A variable declared at module level is therefore shared by all instances of every component that imports the module.
// counter.js
let count = 0;
export function nextId() {
count += 1;
return `item-${count}`;
}If five components call nextId(), they draw from one counter. This is useful for unique IDs. It is a bug if you meant to keep per-component state. Store per-instance state on the class with this, not in the module.
Helpers have no `this` binding to the component
A helper function is not a class method, so this is not the component. If the helper needs component data, pass it as an argument and return a result.
// Avoid: relies on being called with the right `this`
export function buildLabel() {
return `${this.first} ${this.last}`;
}
// Prefer: explicit inputs and outputs
export function buildLabel(first, last) {
return `${first} ${last}`;
}The file name must not shadow the component
Do not name a helper after the folder, and do not add a second file whose base name collides with the main file. Keep the helper's name descriptive, such as greetingFormatter.js rather than utils.js, so imports read clearly when a bundle grows.
Keep the bundle flat
Keep helper files directly in the bundle folder. The __tests__ folder is the standard exception and is excluded from deployment. Nesting other folders inside a bundle is not a pattern to rely on.
Helpers are not Apex or metadata
A helper module runs in the browser as client-side JavaScript. It cannot define Apex logic or change what js-meta.xml exposes. Importing Apex methods or other platform modules works in a helper the same way it does in the main file, but a helper that depends on the platform is harder to test.
Testing a helper
Because a helper is a plain module, a Jest test can import it directly. No createElement call is needed. The test file goes in the bundle's __tests__ folder.
// __tests__/greetingFormatter.test.js
import { formatName, MAX_NAME_LENGTH } from '../greetingFormatter';
describe('formatName', () => {
it('capitalizes the first letter', () => {
expect(formatName('ada')).toBe('Ada');
});
it('trims whitespace', () => {
expect(formatName(' ada ')).toBe('Ada');
});
it('falls back to World for empty input', () => {
expect(formatName(' ')).toBe('World');
expect(formatName(undefined)).toBe('World');
});
it('limits the length', () => {
const long = 'a'.repeat(MAX_NAME_LENGTH + 10);
expect(formatName(long).length).toBe(MAX_NAME_LENGTH);
});
});These tests run faster than component tests and fail with a clear message when a function breaks. To test a service component, import it as c/textUtils or by relative path. The standard LWC Jest setup maps the c/ namespace to your lwc folders.
Summary of rules
- Any extra
.jsfile in a bundle is a plain ES module, and the main file is the one whose base name matches the folder. - Import helpers from the same bundle with a relative path.
- Share code across components through a service component imported as
c/name. - Call helpers from the class, using a getter if the template needs the result.
- Remember that module-level variables are shared by every importer.
Exercise
A component orderSummary has a helper orderMath.js with export function total(lines). A second component, invoiceView, needs the same function. It tries import { total } from 'c/orderSummary' and gets an error that total is not exported. What are two ways to fix this, and which is better if a third component will need it too?
Show answer
c/orderSummary resolves only to the main file of that bundle, which default-exports the component class, so total is not available from it. One fix is to copy the function into invoiceView's bundle, which duplicates code. The other is to move total into a service component such as orderMath, with orderMath.js exporting total and a js-meta.xml with isExposed set to false, and import it with import { total } from 'c/orderMath' in all components. The service component is better with three consumers, because there is one copy to test and maintain.
Exercise
A developer writes <p>{formatName(name)}</p> in a template after importing formatName in the class file. The template fails to compile. Why, and what is the fix?
Show answer
Templates can reference only members of the component class, such as properties and getters. They cannot call imported functions or use call expressions. Add a getter, get displayName() { return formatName(this.name); }, and bind it with {displayName}.
Exercise
A module idGenerator.js declares let count = 0 at the top level and exports nextId(). Two instances of one component each call nextId() once. What IDs do they get, and what does this show about module state?
Show answer
They get item-1 and item-2, assuming the function builds IDs from count. The module is evaluated once and shared, so both instances increment the same variable. State that must be separate for each instance belongs on the class, not at module level.