Isomorphic code refers to application code that runs seamlessly in both client and server environments. To achieve this in Aurelia:
Instead of directly accessing browser-specific globals like document
or window
, use Aurelia's PAL:
import { DOM } from 'aurelia-pal';
export class MyComponent {
activate() {
const div = DOM.createElement('div');
DOM.appendChild(DOM.body, div);
}
}
Aurelia's PAL provides a consistent API for DOM manipulation and other platform-specific tasks, ensuring your code remains environment-agnostic.
Without PAL (Not Isomorphic):
export class MyPage {
activate() {
document.body.appendChild(document.createElement('div'));
}
}
With PAL (Isomorphic):
import { DOM } from 'aurelia-pal';
export class MyPage {
activate() {
DOM.appendChild(DOM.body, DOM.createElement('div'));
}
}
-
Use PAL for DOM Operations: Always use
aurelia-pal
for any DOM-related tasks. -
Conditional Logic: If certain code should only run on the client or server, use environment checks to prevent execution in the other environment.
import { PLATFORM } from 'aurelia-pal'; if (PLATFORM.isBrowser) { // Code specific to the browser }