Skip to content

Astro

sh
pnpm create astro@latest

# 安装依赖
pnpm astro add react tailwind partytown
# 手动安装
# https://docs.astro.build/zh-cn/guides/integrations-guide/

# 升级
pnpm dlx @astrojs/upgrade

public/robots.txt

sh
# 示例:允许所有机器人扫描并索引你的网站。
# 完整语法:https://developers.google.com/search/docs/advanced/robots/create-robots-txt
User-agent: *
Allow: /

变量

astro
---
const pageTitle = "关于我";
---
<html lang="zh">
  <head>
    <meta charset ="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{pageTitle}</title>
  </head>
  <body>
  </body>
</html>

对象渲染

astro
---
const identity = {
  firstName: "莎拉",
  country: "加拿大",
  occupation: "技术撰稿人",
  hobbies: ["摄影", "观鸟", "棒球"],
};
---
<li>我住在{identity.country}。我的职业是{identity.occupation}。</li>

list 渲染

astro
---
const hobbies = ["摄影", "观鸟", "棒球"];
---
<ul>
  {hobbies.map((hobby) => ( <li>{hobby}</li> ))}
</ul>

条件

astro
---
const happy = true;
const goal = 3;
---
{happy && <p>我非常乐意学习 Astro!</p>}

{goal === 3 ? <p>我的目标是在三天内完成。</p> : <p>我的目标不是 3 天。</p>}

css

全局 css

astro
---
import '../styles/global.css';
---

CSS 变量

注意 skillColor 部分

astro
---
const skillColor = "navy";
---

<style define:vars={{skillColor}}>
  .skill {
    color: green;
    color: var(--skillColor);
    font-weight: bold;
  }
</style>

js

astro
<body>
 <script>
   import "../scripts/menu.js";
 </script>
</body>

组件

props

定义

astro
---
const { platform, username } = Astro.props;
---

使用

astro
<Social platform="twitter" username="astrodotbuild" />

slot

astro
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width" />
    <meta name="generator" content={Astro.generator} />
    <title>{pageTitle}</title>
  </head>
  <body>
    <Header />
    <h1>{pageTitle}</h1>
    <slot />
    <Footer />
    <script>
      import "../scripts/menu.js";
    </script>
  </body>
</html>

api

  • import.meta.glob() 从项目中访问文件中的数据
  • getStaticPaths() 批量创建多个页面(路由)
  • getCollection()

client:*

  1. client:load:页面加载时,立即加载并执行 JavaScript
  2. client:visible: 当元素出现在视口(window)中时,JavaScript 才会加载并执行。适用于延迟加载 JavaScript,提高性能。
  3. client:idle:当浏览器空闲时加载并执行 JavaScript,这通常用于非关键的、可延迟的脚本加载。
  4. client:media:只有在指定的媒体查询匹配时,JavaScript 才会加载和执行,适用于响应式设计和优化。

路由

动态 props

假如路径为:src/pages/[tag].astro

然后访问 /astro/vue/react 都能访问到[tag].astro这个页面

astro
---
export async function getStaticPaths() {
  return [
    { params: { tag: "astro" } },
    { params: { tag: "vue" } },
    { params: { tag: "react" } },
  ];
}
---

<p>{JSON.stringify(Astro.params)}</p>

其中 Astro.params 为:{ tag: "astro" }

markdown

自定义 markdown 的布局

astro
---
layout: ../../layouts/MarkdownPostLayout.astro
title: '我的第一篇博客文章'
pubDate: 2022-07-01
---