Htmx 4.0.0 已发布
Htmx 4.0

原始链接: https://four.htmx.org/announcements/2026-08-28-htmx-4.0.0-is-released

htmx 团队发布了 **htmx 4.0.0**。这是一次重大更新,将该库的内核从 `XMLHttpRequest` 迁移到了现代的 `fetch()` API。虽然面向用户的行为与 2.x 版本基本保持一致,但此次更新带来了三项重大变更: * **显式属性继承:** 属性不再默认继承;用户现在必须在属性后添加 `:inherited` 才能将其应用于子元素。 * **标准化事件:** 事件名称已进行统一清理(例如 `htmx:before:request`),以提高一致性。 * **历史记录变更:** 历史记录支持现在默认为重新获取页面,而不是使用 `localStorage`,从而提高了与第三方库的兼容性。 新功能包括原生的 **Morph Swaps**(由 Idiomorph 提供支持)以及用于高级 DOM 更新的 `` 标签。此外,htmx 4 引入了多个新扩展和 **hx-live**——一种轻量级、对 HATEOAS 友好的前端脚本解决方案。 为协助迁移,团队提供了一个 CLI 升级工具 (`npx [email protected] upgrade-check`)。为了防止强制升级,htmx 2.x 仍作为 NPM 上的“最新”版本,而 4.0.0 则作为“next”版本提供。升级是可选的,htmx 2.x 将继续获得支持。

**htmx 4.0** 的发布在 Hacker News 上引发了热烈讨论,凸显出该库作为重型 JavaScript 框架的极简主义、服务端驱动替代方案,依然广受欢迎。 社区反应的主要观点如下: * **理念吸引力:** 用户青睐 htmx 的简洁性及其“不拘一格”的社区精神,这与典型的企业级技术文化形成了鲜明对比。它常与 Go、SQLite 和 Django 等技术栈结合,无需复杂的构建步骤即可创建高响应速度的应用程序。 * **版本跳跃:** 开发者跳过了 3.0 版本,这是一个玩笑,旨在信守此前关于“绝不会发布破坏性的 3.0 版本”的承诺。 * **大语言模型(LLM)因素:** 一个主要的争论焦点在于 LLM 是否降低了对 htmx 的需求。尽管有人认为 LLM 让编写复杂的 JavaScript 变得更容易,但许多开发者认为 htmx 依然更胜一筹,因为它减少了代码的“接触面”,从而产出更易于维护、测试且 Bug 更少的成果。 * **总体情绪:** 虽然一些开发者更偏好全栈单页应用(如 Angular 或 React)的掌控感,但对于那些希望避免不必要前端复杂性的用户而言,htmx 依然是社区的“宠儿”,许多用户称赞它令人耳目一新。
相关文章

原文

The htmx team is very happy to announce the release of htmx 4.0.0! This is the culmination of 8 months of work (plus a game) and we are very happy with the results.

The idea of htmx 4 started to germinate when I decided to create fixi and, in doing so, got more familiar with the fetch() API and async programming in JavaScript. (htmx had always used XMLHttpRequest due to backwards compatibility issues.)

One chance evening I was contacted by Christian, who had some interesting ideas around streaming HTML that got me thinking that moving the internals to fetch() would simplify things for him and for the library in general.
After a bit of work I managed to get Michael and Alex on board, and we were off to the races.

Development has been very smooth. We started a port of fixi + the htmx test suite. Over time, we rediscovered why htmx did many of the things that it did and moved our new implementation closer and closer to the old one. At this point the behavioral differences between 2.x and 4.x are relatively small and where they do diverge we have made explicit choices that we feel will put htmx-based applications in a good spot for being 100-year web services

Note that we are not marking 4.0 as latest in NPM because we do not want to force-upgrade users who are relying on non-versioned CDN URLs for htmx. Instead, 2.x will remain latest and the 4.0 line will remain next until some point in early 2027. The website, however, will reference 4.0.

Major Changes

As mentioned above, htmx 4, from a users viewpoint, is almost identical to htmx 2. There are three major changes:

  • Attribute inheritance is now explicit by default rather than implicit by default (this is the biggest upgrade item)
  • The htmx event names have been standardized & cleaned up. Some advanced users may need to change the events they listen for.
  • History support now does not use localStorage by default (which was a cause of many support headaches). Most people won’t notice this at all.

Internally, we migrated from XMLHttpRequest to fetch() but that should be transparent for most users of htmx.

Attribute Inheritance

In htmx 2 many attributes where “inherited” by default. This allows you to place attributes on parent elements and their behavior will apply to child elements. This behavior, which came from the intercooler.js days, was inspired by CSS and, unsurprisingly, worked out about the same as CSS: powerful but difficult to understand at times.

In htmx 4 attributes are not inherited unless you explicitly say so by adding an :inherited after the attribute name:

<!-- htmx 2 -->
<div hx-confirm="Are you sure?">
    <button hx-delete="/item/1">Delete</button>
</div>

<!-- htmx 4 -->
<div hx-confirm:inherited="Are you sure?">
    <button hx-delete="/item/1">Delete</button>
</div>

This will be the largest upgrade burden in migrating from htmx 2 to htmx 4. To make things easier, we have provided a command line tool to find places you need to mark as inherited.

Note that attributes like hx-disinherit, etc. are no longer required and should be removed.

Events

The events triggered by htmx 2 had grown organically over the life of the librar and were not particuarly well organized, making it difficult to know exactly which event was fired when.

In htmx 4, all events now follow htmx:phase:action[:sub-action]:

htmx 2htmx 4
htmx:beforeRequesthtmx:before:request
htmx:afterRequesthtmx:after:request
htmx:beforeSwaphtmx:before:swap
htmx:afterSwaphtmx:after:swap
htmx:configRequesthtmx:config:request

In addition, the following changes were made:

  • Most error events collapse into htmx:error. HTTP error responses fire htmx:response:error.
  • The htmx:xhr:* events are removed. htmx 4 uses fetch().
  • The htmx:validation:* events are removed in favor of native browser form validation.

The full table is in What’s New in htmx 4.

The command line upgrade checker flags old event names in hx-on attributes and in your JavaScript where it can find them.

History

History support has always been included in htmx, allowing you to implement back-button aware actions with simple attributes. In htmx 2, a cache in localStorage was used to snapshot pages for restoration. Unfortunately a large source of issues was that this snapshot could include DOM mutations by 3rd party JavaScript libraries. When the page was restored, those mutations remained by the underlying JavaScript logic was not.

htmx 4 does not cache pages in localStorage. On back navigation htmx re-fetches the page and swaps it into <body>, or into the [hx-history-elt] element if one is present. This allows 3rd party JavaScript libraries to “just work” in most cases and, with good request caching, is very fast.

If you want local caching instead, we now ship a very complete hx-history-cache extension restores history from sessionStorage and is designed to integrate well with scripting solutions like Alpine.js, etc.

New Features

There are two big new features in htmx 4, both of which we are really excited about:

Morph Swaps

We now support morphing swaps out of the box with htmx. I created idiomorph and nearly included it in htmx 2.x but decided against it. In htmx 4, Michael has done great work improving on that algorithm and integrating it seamlessly into htmx.

<hx-partial>

Another major new feature is the <hx-partial> tag. This tag is similar to out-of-band swaps, but is much clearer when you want do something beyond just replacing a single element with a new version of itself:

<hx-partial hx-target="#messages" hx-swap="beforeend">
    <div>New message</div>
</hx-partial>
<hx-partial hx-target="#count">
    <span>5</span>
</hx-partial>

Extensions

Much of the excitement in htmx 4 is in the extensions. Switching to fetch() internally let us rething how extensions can and should work, and sparked the creation (and recreation) of many new extensions, for example:

  • hx-preload - preload content (e.g. on mouseover) to speed requests up
  • hx-download - native, fetch-based file downloads
  • hx-alpine-compat - smooths over compatibility issues between htmx and Alpine.js
  • hx-history-cache - caches history in sessionStorage, provides Alpine.js compatibility

Additionally, there are three new or updated streaming HTML extensions:

  • hx-sse streams over text/event-stream.
  • hx-ws streams and sends over WebSockets.
  • hx-multipart streams over multipart/mixed

Finally, we decided it was time to try our hand at our own small front-end scripting solution that tightly integrates with htmx. hx-live is inspired by Alpine.js, jQuery and hyperscript, and makes front end scripting pleasant and fun. It even supports what we are calling DOM-based, HATEOAS-friendly reactivity.

There is a new htmax.js bundle in the distribution which packages htmx with the most popular of these in a single file if you don’t want to think about which ones you want to pick.

Upgrading

For a complete upgrade guide see What’s New in htmx 4.

As mentioned earlier, we are providing an upgrade tool to help you:

$ npx [email protected] upgrade-check -- ./templates

File extensions: .html, .php, .js, .ts, .jinja, .jinja2, .j2, .erb, .hbs
Use --ext to add more (e.g. --ext .vue --ext .svelte)

Scanning 1 file(s)...

Found 8 issue(s) in 1 of 1 file(s).
templates/index.html:1: [inheritance] hx-headers needs :inherited suffix (descendant on line 3 has hx-delete) (this looks like a CSRF token; without :inherited the header does not reach child elements and the server rejects the request)
templates/index.html:2: [inheritance] hx-target needs :inherited suffix (descendant on line 3 has hx-delete)
templates/index.html:2: [inheritance] hx-confirm needs :inherited suffix (descendant on line 3 has hx-delete)
templates/index.html:3: [renamed-attr] hx-disable -> rename to hx-ignore (hx-disable now means 'disable during request')
templates/index.html:4: [removed-attr] hx-vars is removed -> use hx-vals with js: prefix
templates/index.html:4: [removed-attr] hx-prompt is removed -> load the hx-prompt extension to keep the same syntax
templates/index.html:9: [old-event] old event name "htmx:afterRequest" -> "htmx:after:request"
templates/index.html:9: [old-api] htmx.addClass() is removed -> use element.classList.add()

We are also shipping an agent skill to assist in upgrading

Installing

htmx 4.0 can be installed via a package manager referencing version 4.0.0, or can be linked via a CDN:


<script src="https://unpkg.com/[email protected]/dist/htmx.min.js"></script>

or Downloaded

LLMs

Like it or not, a lot of people are using LLMs and we are providing the following skills files for LLMs:

(Let’s leave aside if releasing a new version of a library in the LLM era is a good or bad thing!)

Conclusion

We hope you enjoy htmx 4. htmx 2 will continue to be supported indefinitely so don’t feel any pressure to upgrade.

I’d like to thank the following people for all their help with this release:

  • Michael West - Incredible teammate & grug-brained developer
  • Christian Tanul - Inspired htmx 4 & lead the streaming & live extensions
  • Alex Petros - For keeping the ship on an even keel
  • Stephen Mitchell - The genius behind the game
  • Stu Kennedy - Our WebSockets expert
  • André Ahlert Jr. - Providing IDE & Editor Support
  • Dien Hoa Truong - For kicking the tires on early htmx 4 and helping fix many bugs

Upgrade Music

Wouldn’t be an htmx update without upgrade music:

联系我们 contact @ memedata.com