分类 前端开发 下的文章

Astro 最迷人的地方在于:默认零 JavaScript,但在需要交互的地方又能精准注水。配合视图过渡(View Transitions),页面切换可以达到接近 SPA 的丝滑感。

岛屿架构

传统的 MPA 每次导航都要重新解析全部资源;Astro 的岛屿(Islands)让交互组件独立水合:

---
// 一个交互组件只在进入视口时才加载 JS
import SearchBox from '../components/SearchBox.astro';
---
<SearchBox client:visible />

零依赖的客户端脚本

Astro 的 <script> 标签会被打包、去重并按需加载,用原生 API 就能实现大部分交互:

// 目录高亮:IntersectionObserver 监听标题可见性
const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) activate(entry.target.id);
  }
}, { rootMargin: '-15% 0px -70% 0px' });

document.querySelectorAll('.md-body h2[id]').forEach((h) => observer.observe(h));

实测数据

  • [x] 首页 LCP 稳定在 0.4s 以内
  • [x] 全站 JS 体积 < 30KB gzip
  • [ ] 把 TOC 滚动监听换成 CSS scroll driven animations
  • [ ] 试试浏览器原生的 View Transition API

性能优化的最高境界不是优化,而是从一开始就不发送多余的代码。

—— 某位前端工程师的碎碎念

Tailwind 4 把配置从 tailwind.config.js 搬进了 CSS 本身,@theme 指令让设计令牌真正成为 CSS 变量。

主题即变量

@import "tailwindcss";

@theme {
  --color-neon-400: #22d3ee;
  --font-mono: ui-monospace, "SF Mono", Menlo, monospace;
  --shadow-glow: 0 8px 40px -8px rgb(34 211 238 / 0.35);
}

声明后即可直接使用 text-neon-400、shadow-glow 这些工具类,运行时还能用 var(--color-neon-400) 引用。

与 Astro 的组合

// astro.config.mjs
import tailwindcss from '@tailwindcss/vite';

export default {
  vite: { plugins: [tailwindcss()] },
};

不需要 PostCSS 配置,不需要 content 扫描白名单,Vite 插件搞定一切。

一些值得注意的迁移点

  • @apply 依然可用,但自定义类要先 @utility 注册
  • 默认边框颜色从 gray-200 变为 currentColor
  • 渐变工具类从 bg-gradient-to-r 改名为 bg-linear-to-r

整体感受:4.0 是一次「减法」升级,心智负担反而更小了。