Jerry's Blog

Back

优化你的站点

提升网站性能和用户体验

集成#

本主题已集成:

CDN#

一些轻量级库使用了 JS 静态链接。你可以配置 CDN 链接来提升站点性能。

src/site.config.ts
export const theme: ThemeUserConfig = {
  // ...
  npmCDN: 'https://cdn.jsdelivr.net/npm'
  // 推荐:
  // - https://cdn.jsdelivr.net/npm
  // - https://cdn.smartcis.cn/npm
  // - https://unkpg.com
  // - https://cdn.cbd.int
}
ts

编码#

.astro 文件中使用“类似 TypeScript”的注释是一个好方法。这可以确保你的注释不会在最终的生成 HTML 文件中被渲染出来。

---
// 这里是可以安全放置注释的地方
import { AstroComponent } from '@/components'
---

<div>
  <!-- 这是一种不好的注释风格,它仍会出现在生产版本中 -->
  {/* 这是一种更好的注释风格 */}
  <AstroComponent>Hello, Astro!</AstroComponent>
</div>
astro

图片#

使用优化组件#

使用 <Image /> 组件显示优化后的图片:使用 Astro 内置的 <Image /> 组件 来显示以下内容的优化版本:

  • 位于 src/ 文件夹中的本地图片
  • 来自授权来源的配置远程图片

<Image /> 可以转换本地或授权远程图片的尺寸、文件类型和质量,以便控制显示的图片。生成的 <img> 标签包含 alt、loading 和 decoding 属性,并推断图片尺寸以避免累积布局偏移(CLS)。

你可以使用 loading="lazy" 来为图片启用懒加载。

src/pages/somepage.astro
---
// 导入 Image 组件和图片
import { Image } from 'astro:assets'

import myImage from '../assets/my_image.png' // 图片尺寸 1600x900
---

<!-- `alt` 属性在 Image 组件中是必需的 -->
<Image src={myImage} alt='我的图片描述。' />
astro
<!-- 输出 -->
<img
  src="/_astro/my_image.hash.webp"
  width="1600"
  height="900"
  decoding="async"
  loading="lazy"
  class="my-class"
  alt=""
/>
html

使用这种方式,它会将你的图片转换为 WebP 格式。.md.mdx 文件默认已启用此功能。

改变图片大小#

虽然本主题已集成了一些知名的图片优化插件,但你仍可能需要对一些关键页面(如首页)的图片进行优化。

一种简单的方法是使用在线工具,如 TinyPNG,手动压缩你的图片。

适配外部图片#

如果你使用外部图片,除了添加懒加载标签外,你还可以为其添加 Astro 预优化服务。这会将外部图片转换为本地优化后的图片。

astro.config.ts
export default defineConfig({
  // ...
  image: {
    // ...
    domains: ['<特定站点域名>'] 
  }
})
js

文件大小分析#

安装 npm 包 rollup-plugin-visualizer。然后将以下代码添加到你的 astro.config.ts 中:

astro.config.ts
export default defineConfig({
  // ...
  vite: {
    plugins: [
      visualizer({
        emitFile: true,
        filename: 'stats.html'
      })
    ]
  }
})
ts

构建你的项目,然后打开生成的 stats.html 文件来分析你的打包体积。分析完成后,你可以移除上述代码和包,以保持项目整洁。