@ecopages/browser-router

中文文档
0.7.1发布于 2026/11/13MITTypeScriptES Module构建来源已验证近 30 天下载 3301

Client-side router for Ecopages with view transitions support

原始使用文档
文档目录13 节
  1. Features
  2. Compatibility
  3. Installation
  4. Usage
  5. Router singleton
  6. Configuration
  7. Persistence
  8. Reloading the current page
  9. Scripts on navigation
  10. Script Re-execution
  11. Force Full Reload
  12. Events
  13. Programmatic Navigation

@ecopages/browser-router

Client-side navigation and view transitions for Ecopages. It intercepts same-origin link clicks to provide smooth page transitions without full page reloads.

Features

  • Client-side navigation: Intercepts <a> clicks for robust, fast navigation.
  • Efficient DOM diffing: Uses morphdom to update only what changed, preserving scroll positions and internal state.
  • State persistence: Elements with data-eco-persist are never recreated, preserving Web Component state, event listeners, and form values.
  • View Transitions: Optional integration with the View Transition API.
  • Lifecycle events: Hook into navigation with eco:before-swap, eco:after-swap, eco:page-load.

The core navigation pipeline shares document fetching, parsing, head reconciliation, stylesheet staging, script activation, named view transitions, and lifecycle events with @ecopages/react-router. Browser-router always morphs the incoming body, preserving persisted elements across navigation regardless of view-transition settings or rerun scripts. View transitions only wrap the morph; scroll restoration uses the shared post-swap hook.

Browser-router keeps its own cache of prefetched and visited pages: a revisit renders the cached HTML immediately, and the cached copy is not refreshed in the background. Set prefetch: false to turn the cache off, so every navigation fetches fresh HTML. @ecopages/react-router does not read this cache and always fetches fresh HTML.

Compatibility

This package is designed for MPA-style rendering where the server returns full HTML pages (e.g., KitaJS, Lit, vanilla JS, or component-level React islands).

[!WARNING] Not compatible with full React applications. If you are building a React application, use @ecopages/react-router instead, as React manages its own virtual DOM and hydration lifecycle.

[!NOTE] @ecopages/browser-router can still participate in mixed sites that contain both React-router pages and non-React pages. In that setup, browser-router remains responsible for DOM-swapping non-React documents, and React-router can hand off already-fetched non-React pages to it through the shared navigation coordinator.

Installation

bun add @ecopages/browser-router

Usage

Create and start the router in a global client-side script (e.g., src/layouts/base-layout.script.ts).

[!IMPORTANT] Ensure the router script is injected in a consistent order within the <head> across all pages. Inconsistent ordering causes morphdom to reload styles, leading to a "Flash of Unstyled Content" (FOUC).

import { createRouter } from '@ecopages/browser-router/client';

// Creates and starts the router with default options
const router = createRouter();

With custom options:

import { createRouter } from '@ecopages/browser-router/client';

const router = createRouter({
    viewTransitions: true,
    scrollBehavior: 'auto',
    documentElementAttributesToSync: ['lang', 'dir', 'data-theme'],
});

By default, when view transitions are enabled, the router opts the document out of the UA root group (no lighter flash on dark themes) and only calls startViewTransition when a page uses data-view-transition shared-element morphs. Set viewTransitions: false to disable.

By default, browser-router only syncs root <html> metadata it owns. Client-managed attributes and classes such as theme state are preserved unless you explicitly include them in documentElementAttributesToSync.

For advanced cases, browser-router also exports low-level document sync tooling without changing the router instance API:

import {
    createRouter,
    DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
    syncDocumentElementAttributes,
} from '@ecopages/browser-router';

const router = createRouter();

document.addEventListener('eco:before-swap', (event) => {
    syncDocumentElementAttributes(document, event.detail.newDocument, [
        ...DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
        'data-theme',
    ]);
});

Loading the router script is the opt-in point for browser-router-managed navigation on that page shell. Pages without the router script continue to use normal document navigation.

Router singleton

createRouter() returns a single active router per browser tab. The first call creates, starts, and stores the instance on window.__ecopages_browser_router__. Later calls return that same instance and ignore new options.

Call router.stop() before replacing the router script in long-lived sessions (for example after data-eco-rerun layout reloads) if you need a fresh instance with different options.

Configuration

OptionTypeDefaultDescription
linkSelectorstring'a[href]'Selector for links to intercept
documentElementAttributesToSyncstring[]['lang', 'dir', 'data-eco-document-owner']<html> attributes to sync from the incoming document; other root attributes are preserved
persistAttributestring'data-eco-persist'Attribute to mark elements for DOM persistence
reloadAttributestring'data-eco-reload'Attribute to force full page reload
updateHistorybooleantrueWhether to update browser history
scrollBehavior'top' | 'preserve' | 'auto''top'Scroll behavior after navigation
viewTransitionsbooleantrueView Transition API; disables UA root crossfade by default. false disables.
smoothScrollbooleanfalseUse smooth scrolling during navigation
reloadDocument(href: string) => void(href) => window.location.assign(href)Loads a URL as a full document when the router hands a navigation back to the browser

Persistence

Mark elements with the same persistence key on each page to preserve them across navigations. When the incoming page keeps the element under a compatible ancestor structure, it stays connected and is never recreated; morphdom skips it entirely. This holds when view transitions are disabled and when the incoming page has data-eco-rerun scripts. Changing the element's ancestor tags can require replacing its containing path, so keep that structure stable when connection continuity matters.

On navigation to another URL, when an incoming page has a data-eco-rerun script, browser-router refreshes matching non-persisted elements before running it, except for the body, persisted elements, their ancestor path, and descendants of custom elements on that path. Those custom-element descendants stay in place because the connected host may have attached handlers to them. Keep handler-bound child markup structurally compatible across pages, or have the component rebind when its child markup changes; replacing a child does not reconnect the host. Event handlers installed on refreshed elements attach to new nodes instead of stacking on nodes retained by the morph. A rerun script that installs handlers on any retained node must make that registration idempotent, because those nodes remain attached across navigations.

<!-- This counter keeps its internal state across all navigations -->
<radiant-counter data-eco-persist="counter"></radiant-counter>

Reloading the current page

reloadCurrentPage() on the navigation runtime, which development HMR calls when a server-rendered template such as a page, layout, include or view is saved, and when a module update reloads the active page (clearCache: false), fetches the current URL again and compares each body element's server markup in the previous document with its markup in the new one, rather than with the live element. An element whose server markup did not change stays as it is, with its state, children, shadow root and runtime attributes; a changed custom element is replaced, and a changed plain element is morphed, keeping its live attributes when its own server attributes did not change. Rerun scripts do not refresh elements on a reload, so a data-eco-rerun script must register handlers idempotently on every element a reload does not replace, which is all but changed custom elements. Navigation to another URL morphs as described above. The router records server markup only after development HMR calls enableReloadStatePreservation() on the navigation runtime, so production navigations copy nothing.

Known limits:

  • The first save after a full page load compares against the body as the router found it when recording started, so a component that rendered or changed its attributes on the client before then is replaced once.
  • State follows tree position, so identical sibling hosts can swap state when an earlier sibling is inserted or removed.

Scripts on navigation

After the swap, a head script runs only if the previous page's head did not have it, and body scripts run on every navigation, as in Turbo: the body is new content even when the previous page had the same script. That covers inline scripts and external classic scripts; an external module script runs only once per URL in a tab, because the browser evaluates each module URL once. A classic script's top-level const, let and class declarations live in the page's global scope, so when a classic body script runs again they are declared twice and throw SyntaxError: Identifier '…' has already been declared. Write such a script without them (use var or functions, or wrap the code in a block or an IIFE), or make it a module script, which runs once per URL, and listen for eco:page-load for code that must run on each visit. A script inside an element marked data-eco-persist is kept as it was and does not run again. Scripts run in one sequence: new head scripts, then data-eco-rerun scripts, then body scripts, each group in document order. Each waits until earlier blocking scripts (external classic scripts without async, defer, or nomodule) have loaded, as during page parsing, so an inline script that uses a library the page loads runs after it. External defer and module scripts keep that insertion order too; only scripts the page marks async run as soon as they load. If the next navigation swaps the page while a script is still loading, the rest of the previous sequence does not run.

Script Re-execution

To force a head script to re-execute on every navigation (e.g., analytics), add data-eco-rerun:

<script data-eco-rerun="true">
    trackPageview();
</script>

[!NOTE] data-eco-script-id is optional. Use it when you want an explicit stable identity for a rerun script. Without it, an HTML id takes precedence; otherwise the router matches by original src or inline content. When matching by a relative src, the identity stays the same across different <base> URLs, while an external module reruns from the incoming page's resolved URL.

Force Full Reload

Use data-eco-reload on an anchor tag to bypass the router and force a full page reload:

<a href="/logout" data-eco-reload>Logout</a>

Events

Listen to navigation lifecycle events on the document. Event detail types live in @ecopages/core/client.

document.addEventListener('eco:before-swap', (e) => {
    console.log('Navigating to:', e.detail.url);
    // Call e.detail.reload() to abort client-side navigation and do a full reload
});

document.addEventListener('eco:after-swap', (e) => {
    console.log('Swapped to:', e.detail.url);
});

document.addEventListener('eco:page-load', (e) => {
    console.log('Page loaded:', e.detail.url);
});

e.detail.newDocument is the parsed incoming document and a listener may change it. Custom elements the router inserts or replaces are the nodes of that document themselves, so properties you set on them, and their nested nodes, are still there when the browser upgrades and connects them:

document.addEventListener('eco:before-swap', (e) => {
    const host = e.detail.newDocument.querySelector('my-host');
    if (host) host.engine = engine;
});

Elements the router keeps in place, such as persisted elements, ignore properties set on their incoming counterpart. A property set before an element upgrades shadows a class accessor of the same name and is reset by a class field of that name: the component should read the own value, delete it and assign it through the accessor in its constructor.

Programmatic Navigation

Use the router instance to navigate programmatically:

import { createRouter } from '@ecopages/browser-router/client';

const router = createRouter();

// Navigate with pushState
await router.navigate('/new-page');

// Navigate with replaceState
await router.navigate('/new-page', { replace: true });

版本与发布记录

@ecopages/browser-router 共发布 126 个版本,首次发布于 2026/03/09;过去 12 个月发布了 126 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.1latest2026/11/13今天
0.7.02026/11/094 天前
0.6.12026/10/3014 天前
0.6.02026/10/2915 天前
0.5.02026/10/2420 天前
0.4.02026/10/2222 天前

其他发布通道:alpha → 0.2.0-alpha.55,beta → 0.2.0-beta.43,rc → 0.2.0-rc.14。

关于 @ecopages/browser-router 的常见问题

@ecopages/browser-router 是什么?

Client-side router for Ecopages with view transitions support

如何安装 @ecopages/browser-router?

在项目目录运行 npm install @ecopages/browser-router,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@ecopages/core(0.7.1)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ecopages/browser-router 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ecopages/browser-router 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@ecopages/browser-router 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^24.22.0 || >=26.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ecopages/browser-router 可以商用吗?

@ecopages/browser-router 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ecopages/browser-router 的下载量有多少?

根据 npm 官方下载统计,@ecopages/browser-router 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,301 次,日均约 110 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ecopages/browser-router 还在维护吗?

最新版本 0.7.1 发布于 2026/11/13(今天);至今共发布 126 个版本,其中过去 12 个月发布了 126 个;首次发布于 2026/03/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。