Astro配置 #

一、配置文件概述 #

1.1 配置文件位置 #

Astro 配置文件通常位于项目根目录,命名为 astro.config.mjs

text
my-project/
├── astro.config.mjs    # 主配置文件
├── package.json
├── tsconfig.json
└── src/

1.2 基本配置结构 #

javascript
import { defineConfig } from 'astro/config';

export default defineConfig({
  // 配置选项
});

二、核心配置选项 #

2.1 site(站点 URL) #

设置站点的完整 URL,用于生成规范链接和社交分享:

javascript
import { defineConfig } from 'astro/config';

export default defineConfig({
  site: 'https://example.com',
});

使用示例:

astro
---
// 在组件中获取站点 URL
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<link rel="canonical" href={canonicalURL} />

2.2 root(项目根目录) #

设置项目根目录,默认为当前目录:

javascript
export default defineConfig({
  root: '.',  // 默认值
});

2.3 srcDir(源码目录) #

设置源代码目录,默认为 ./src

javascript
export default defineConfig({
  srcDir: './src',  // 默认值
});

2.4 publicDir(静态资源目录) #

设置静态资源目录,默认为 ./public

javascript
export default defineConfig({
  publicDir: './public',  // 默认值
});

2.5 outDir(输出目录) #

设置构建输出目录,默认为 ./dist

javascript
export default defineConfig({
  outDir: './dist',  // 默认值
});

2.6 output(输出模式) #

设置输出模式,支持三种模式:

模式 说明
static 静态站点(默认)
server 服务端渲染(SSR)
hybrid 混合渲染
javascript
export default defineConfig({
  output: 'static',  // 默认值
});

三、服务器配置 #

3.1 开发服务器配置 #

javascript
export default defineConfig({
  server: {
    host: 'localhost',    // 主机地址
    port: 4321,           // 端口号
    open: false,          // 是否自动打开浏览器
    headers: {            // 自定义响应头
      'X-Custom-Header': 'value',
    },
  },
});

3.2 SSR 服务器配置 #

javascript
export default defineConfig({
  output: 'server',
  adapter: vercel(),  // 使用适配器
  
  server: {
    host: true,  // 监听所有地址
    port: 3000,
  },
});

四、集成配置 #

4.1 添加集成 #

javascript
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
import tailwind from '@astrojs/tailwind';
import sitemap from '@astrojs/sitemap';

export default defineConfig({
  integrations: [
    react(),
    tailwind(),
    sitemap(),
  ],
});

4.2 集成配置选项 #

javascript
import { defineConfig } from 'astro/config';
import tailwind from '@astrojs/tailwind';
import mdx from '@astrojs/mdx';

export default defineConfig({
  integrations: [
    tailwind({
      applyBaseStyles: false,  // 禁用基础样式
    }),
    mdx({
      extendMarkdownConfig: true,
    }),
  ],
});

4.3 条件集成 #

javascript
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';

const integrations = [];

// 仅在生产环境添加某些集成
if (process.env.NODE_ENV === 'production') {
  integrations.push(sitemap());
}

export default defineConfig({
  integrations,
});

五、Vite 配置 #

5.1 自定义 Vite 配置 #

Astro 基于 Vite 构建,可以自定义 Vite 配置:

javascript
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    css: {
      devSourcemap: true,
    },
    build: {
      cssMinify: true,
    },
    resolve: {
      alias: {
        '@': '/src',
        '@components': '/src/components',
      },
    },
  },
});

5.2 常用 Vite 配置 #

javascript
export default defineConfig({
  vite: {
    // CSS 配置
    css: {
      modules: {
        localsConvention: 'camelCase',
      },
    },
    
    // 开发服务器配置
    server: {
      watch: {
        ignored: ['**/node_modules/**'],
      },
    },
    
    // 构建配置
    build: {
      minify: 'esbuild',
      target: 'esnext',
    },
    
    // 优化配置
    optimizeDeps: {
      include: ['lodash'],
      exclude: ['your-linked-package'],
    },
  },
});

六、图片配置 #

6.1 图片服务配置 #

javascript
export default defineConfig({
  image: {
    // 图片服务
    service: {
      entrypoint: 'astro/assets/services/sharp',
    },
    
    // 远程图片域名白名单
    domains: ['example.com', 'cdn.example.com'],
    
    // 远程图片路径正则
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.example.com',
      },
    ],
  },
});

6.2 图片使用示例 #

astro
---
import { Image } from 'astro:assets';
import heroImage from '../images/hero.png';
---

<Image 
  src={heroImage} 
  alt="Hero" 
  width={800} 
  height={600} 
/>

七、Markdown 配置 #

7.1 Markdown 选项 #

javascript
export default defineConfig({
  markdown: {
    // 语法高亮
    syntaxHighlight: 'shiki',  // 'shiki' | 'prism' | false
    
    // shiki 配置
    shikiConfig: {
      theme: 'github-dark',
      wrap: true,
    },
    
    // GitHub 风格 Markdown
    gfm: true,
    
    // 自定义渲染器
    remarkPlugins: ['remark-code-titles'],
    rehypePlugins: ['rehype-autolink-headings'],
  },
});

7.2 自定义 Markdown 插件 #

javascript
import remarkToc from 'remark-toc';
import rehypeSlug from 'rehype-slug';

export default defineConfig({
  markdown: {
    remarkPlugins: [
      [remarkToc, { tight: true }],
    ],
    rehypePlugins: [
      rehypeSlug,
    ],
  },
});

八、路由配置 #

8.1 重定向 #

javascript
export default defineConfig({
  redirects: {
    '/old-page': '/new-page',
    '/blog/old-post': '/blog/new-post',
    '/old/[slug]': '/new/[slug]',
  },
});

8.2 预渲染路由 #

在 SSR 模式下预渲染特定路由:

javascript
export default defineConfig({
  output: 'hybrid',
  
  prerender: {
    entries: [
      '/',
      '/about',
      '/blog',
      '/blog/[slug]',
    ],
  },
});

九、国际化配置 #

9.1 i18n 配置 #

javascript
export default defineConfig({
  i18n: {
    defaultLocale: 'zh',
    locales: ['zh', 'en', 'ja'],
    routing: {
      prefixDefaultLocale: false,
    },
  },
});

9.2 使用国际化 #

astro
---
const { locale } = Astro.currentLocale;
---

<html lang={locale}>
  <body>
    {locale === 'zh' && <p>你好</p>}
    {locale === 'en' && <p>Hello</p>}
  </body>
</html>

十、实验性功能 #

10.1 启用实验性功能 #

javascript
export default defineConfig({
  experimental: {
    // 启用内容层
    contentLayer: true,
    
    // 启用其他实验性功能
    directRenderScript: true,
  },
});

十一、完整配置示例 #

11.1 博客项目配置 #

javascript
import { defineConfig } from 'astro/config';
import tailwind from '@astrojs/tailwind';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';
import remarkToc from 'remark-toc';
import rehypeSlug from 'rehype-slug';

export default defineConfig({
  site: 'https://myblog.com',
  
  integrations: [
    tailwind(),
    mdx(),
    sitemap(),
  ],
  
  markdown: {
    shikiConfig: {
      theme: 'github-dark',
    },
    remarkPlugins: [[remarkToc, { tight: true }]],
    rehypePlugins: [rehypeSlug],
  },
  
  image: {
    domains: ['cdn.myblog.com'],
  },
  
  vite: {
    resolve: {
      alias: {
        '@': '/src',
      },
    },
  },
});

11.2 文档站点配置 #

javascript
import { defineConfig } from 'astro/config';
import tailwind from '@astrojs/tailwind';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';
import react from '@astrojs/react';

export default defineConfig({
  site: 'https://docs.example.com',
  
  integrations: [
    tailwind(),
    mdx(),
    sitemap(),
    react(),
  ],
  
  markdown: {
    shikiConfig: {
      theme: 'github-light',
      wrap: true,
    },
  },
  
  vite: {
    resolve: {
      alias: {
        '@components': '/src/components',
        '@layouts': '/src/layouts',
      },
    },
  },
});

11.3 SSR 应用配置 #

javascript
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/server';
import react from '@astrojs/react';

export default defineConfig({
  site: 'https://app.example.com',
  
  output: 'server',
  adapter: vercel(),
  
  integrations: [
    react(),
  ],
  
  server: {
    host: true,
    port: 3000,
  },
  
  vite: {
    ssr: {
      noExternal: ['some-package'],
    },
  },
});

十二、环境变量配置 #

12.1 使用环境变量 #

javascript
import { defineConfig } from 'astro/config';

const site = process.env.SITE_URL || 'https://example.com';

export default defineConfig({
  site,
  
  integrations: process.env.NODE_ENV === 'production' 
    ? [sitemap()] 
    : [],
});

12.2 .env 文件 #

bash
# .env
SITE_URL=https://example.com
API_URL=https://api.example.com

十三、配置最佳实践 #

13.1 配置文件组织 #

javascript
// astro.config.mjs
import { defineConfig } from 'astro/config';

// 导入集成
import integrations from './astro/integrations';
import viteConfig from './astro/vite';

export default defineConfig({
  site: 'https://example.com',
  integrations,
  vite: viteConfig,
});

13.2 类型安全配置 #

typescript
// astro.config.ts
import type { AstroUserConfig } from 'astro';

const config: AstroUserConfig = {
  site: 'https://example.com',
};

export default config;

十四、总结 #

Astro 配置核心要点:

text
┌─────────────────────────────────────────────────────┐
│                 配置核心要点                         │
├─────────────────────────────────────────────────────┤
│                                                     │
│  📁 site      站点 URL,用于规范链接                │
│                                                     │
│  📤 output    输出模式:static/server/hybrid        │
│                                                     │
│  🔌 integrations 集成配置                          │
│                                                     │
│  ⚡ vite     Vite 构建配置                          │
│                                                     │
│  📝 markdown Markdown 渲染配置                     │
│                                                     │
│  🖼️ image    图片处理配置                          │
│                                                     │
└─────────────────────────────────────────────────────┘

下一步,让我们学习 模板基础,掌握 Astro 模板语法!

最后更新:2026-03-28