你可能不需要 Astro

3,998 阅读3分钟

astro 卷吗?

2022年9月28日,astro版本 v1.1

  • 问:astro 卷吗?
  • 答:卷!
  • 问:为什么?
  • 答:并非新概念!
  • 问:要学习吗?
  • 答:可以学习!

本文追求简单,快速阅读,定位非技术文档,跟多倾向原理,但不探索原理细节

Astro 特点

  • 静态、支持局部动态[岛架构(局部js动态渲染)]
  • 由 vite 驱动的多框架支持
  • 对 markdown/mdx 支持,渲染快速
  • ...

岛架构设计文章与框架

本质

  • 多页面框架
  • HTML/CSS 优先快速渲染占据
  • 自创 astro 单文件,支持多种文件页面文件
  • 支持各种前端组件(使用时要注意,可能与想象的有所区别,最后有 node ssr 渲染经验)

适合场景(主静态/少交互)

  • 博客
  • 文档
  • 其他的静态页面
  • 其他交互不强的追求速度的页面

如果要实现一个博客系统(用于学习,尝试不同技术栈):

  • 前端用 astro 静态渲染
  • 后台管理用 使用 React/Vue/...
  • 后端使用 (express/nestjs/koa...)

可以自己实现一个博客系统,在博客前端考虑使用 astro 渲染

astro 语法特点

  • JSX like 如果开发过 React/PReact 之类的会特别熟悉
  • slot 支持插槽
  • html/mardown/Frontmatter

手动体验

以 pnpm 为包管理工具来创建一个目录:

  • 安装
mkdir your_project_dir
cd your_project_dir

pnpm init
pnpm install astro @astrojs/react @astrojs/tailwind
  • 添加脚本
"scripts": {
  "dev": "astro dev",
  "start": "astro dev",
  "build": "astro build",
  "preview": "astro preview"
}
  • 运行开发服务
pnpm dev
  • 添加一个 astro 页面
---
import Home from '../components/home'
---
<html>
  <body>
    <Home></Home>
  </body>
</html>
<style>
  h1 {
    color: orange;
  }
</style>

这里的 Home 是一个 React Function 组件,注意此时 React Function 组件中的状态、副作用 都失效了,因为 React 静态渲染之后只有 html。

注意:JavaScript 脚本写在 markdown 的 Frontmatter 里

集成

image.png

astro 中集成了主流的框架

下面集成 React/Tailwindcss 为例:

pnpm install @astrojs/tailwind @astrojs/tailwind
  • astro 配置文件
import { defineConfig } from 'astro/config'
import react from '@astrojs/react'
import tailwind from '@astrojs/tailwind'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

// https://astro.build/config
export default defineConfig({
  integrations: [react(), tailwind()],
  resolve: {
    alias: [
      { find: /^~/, replacement: '' },
      { find: '@', replacement: path.resolve(__dirname, 'src') }
    ]
  },
  output: 'server',
  server: {
    port: 3001,
    proxy: {
      '/static': {
        target: 'http://localhost:9999',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/static/, '/static')
      }
    }
  }
})

pnpm workspaces 包说明

/packages/* 包说明
astro核心
astro-prismprismjs 实现代码高亮
astro-rssrss 订阅
create-astro创建 astro 项目
integrations集成前端库等
markdownmd 工具
telemetry设置当前 CLI 用户的遥测配置。遥测是匿名数据,为 Astro 团队提供对哪些 Astro 功能最常用的见解。(感觉不是很香了)
webapiWeb api 在 Node v12, v14, and v16.

从 cli 启动

  • packages\astro\astro.js
if (supportsESM) {
    return import('./dist/cli/index.js')
    .then(({ cli }) => cli(process.argv))
    .catch((error) => {
            console.error(error);
            process.exit(1);
    });
}

支持的命令: dev/build/check/preview

  • packages\astro\src\cli\index.ts
switch (cmd) {
    case 'dev': {
        // 此处启动了开发服务所需要的 devServer, 应用从这里开始解析编译
    }
    case 'build': {
        return await build(astroConfig, { logging, telemetry });
    }
    case 'check': {
        const ret = await check(astroConfig);
        return process.exit(ret);
    }
    case 'preview': {
        const server = await preview(astroConfig, { logging, telemetry });
        return await server.closed(); // keep alive until the server is closed
    }
}

这里只是抛砖引玉,对 astro 源码感兴趣的可以进一步探索细节

telemetry 遥感技术

遥感技术就是搜集 astro 使用的相关信

其中一个核心方法 record:

async record(event: TelemetryEvent | TelemetryEvent[] = []) {
    return post({
        context,
        meta,
        events,
    }).catch((err) => {
        // Log the error to the debugger, but otherwise do nothing.
        this.debug(`Error sending event: ${err.message}`);
    });
}

record 调用的 post 方法, 会向 https://telemetry.astro.build/api/v1/record 地址提交数据:

import fetch from 'node-fetch';

const ASTRO_TELEMETRY_ENDPOINT = `https://telemetry.astro.build/api/v1/record`;

export function post(body: Record<string, any>): Promise<any> {
    return fetch(ASTRO_TELEMETRY_ENDPOINT, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: { 'content-type': 'application/json' },
    });
}

控制遥感技术行为

  • 使用子命令 telemetry
astro telemetry disable # 禁用遥感技术
astro telemetry enable # 启动遥感技术
astro telemetry clear # 重置遥感技术

源码中 telemetry 设计的文件

image.png

遥感技术是一个敏感的技术,提供了一个新的点,

小结

  • 一篇关于 astro 初步入门的文章,简单阅读快速
  • 抛砖引玉式的书写,不是处理细节,希望读者自己探索
  • 引出 astro 遥感技术

参考