Skip to content

Isomorphism

thednp edited this page Apr 19, 2025 · 2 revisions

The vite-plugin-vanjs provides isomorphic capabilities, allowing your code to run in both server and client environments while automatically loading the appropriate modules.

Module Aliases

For convenience, you can use these special module aliases:

  • @vanjs/van - replaces vanjs-core imports
  • @vanjs/vanX - replaces vanjs-ext imports

Basic Example

// my-component.ts
import van from '@vanjs/van';

// use van as usual
const MyComponent = () => {
  return van.tags.div("Hello from VanJS!");
};

Reactive Components

// my-list.ts
import van from '@vanjs/van';
import vanX from '@vanjs/vanX';

type ListItem = { text: string, done: boolean };

// use VanJS as usual
const MyList = () => {
  const items = vanX.reactive<ListItem[]>([]);
  const { div, button, span, a, input, del } = van.tags;
  const inputDom = input({ type: "text", placeholder: "your new item" });
  return div(
    inputDom,
    button({onclick: () => items.push({text: inputDom.value, done: false})}, "Add"),
    vanX.list(div, items, ({val: v}, deleter) => div(
      input({type: "checkbox", checked: () => v.done, onclick: (e) => v.done = e.target.checked}),
      () => (v.done ? del : span)(v.text),
      button({ onclick: deleter }, "Remove"),
    )),
  )
};

Environment Detection

The @vanjs/setup module provides an isServer property to help with environment-specific code:

import { isServer } from '@vanjs/setup';

if (!isServer) {
  // Client-only code here
}

Notes

  • The plugin automatically replaces imports from vanjs-core with @vanjs/van;
  • Similarly, vanjs-ext imports are replaced with @vanjs/vanX;
  • Use isServer from @vanjs/setup to conditionally execute code based on environment;
  • Anywhere you have vite-plugin-vanjs enabled in your vite apps, most plugins and components should work isomorphically.

Clone this wiki locally