Astro 环境变量与配置
使用环境变量
读取环境变量
把密钥、开关等敏感或随环境变化的值放进 .env 文件,代码里用 import.meta.env 读取。
# .env
API_KEY=abc123
SITE_TITLE=我的站点
在组件或脚本里:
---
const key = import.meta.env.API_KEY;
const title = import.meta.env.SITE_TITLE;
---
变量前缀与暴露范围
Astro 用前缀决定变量能否出现在浏览器端:
PUBLIC_开头的变量:会打包进客户端,浏览器可见。例如PUBLIC_API_URL。- 其他变量:只在服务端可用,不会泄露到浏览器,适合放密钥。
PUBLIC_API_URL=https://api.example.com
SECRET_KEY=不要给别人看
SECRET_KEY 只能在构建/服务端脚本里用,绝不会发到浏览器。
不同环境的配置文件
可以准备多份文件区分环境:
.env:默认.env.production:生产环境.env.development:开发环境
Astro 会根据当前模式自动加载对应文件。
项目配置
核心配置文件
项目主配置是 astro.config.mjs,常用项包括:
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
site: 'https://example.com',
integrations: [react()], // 集成 React,使 Astro 可混用 React 组件
markdown: {
shikiConfig: { theme: 'github-dark' }, // 配置 Markdown 代码块的高亮主题
},
});
site:站点正式域名,用于生成绝对链接和站点地图(Astro 站点配置与 SEO)。integrations:集成各种框架或功能(React、MDX、Tailwind 等)。markdown:配置 Markdown 渲染行为。
路径别名
在 tsconfig.json 里配置别名,写 import 更清爽。
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"] // 把 @ 映射到 src,写 import 更简洁
}
}
}
之后可以用 import Card from '@/components/Card.astro'。