Astro Theme Pure

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-like” 语法注释是一个好方法。它可以确保您的注释不会出现在最终的生产 HTML 文件中。

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

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

图片#

使用优化组件#

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

  • 位于 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 文件来分析您的包大小。完成后,您可以删除上述代码和包以保持项目清洁。