Astro 통합 API
Astro 통합은 몇 줄의 코드만으로 프로젝트에 새로운 기능과 동작을 추가합니다.
이 참조 페이지는 자체 통합을 작성하는 모든 사용자를 위한 것입니다. 프로젝트에서 통합을 사용하는 방법을 배우려면 통합 사용 가이드를 대신 확인하세요.
공식 Astro 통합은 자체 통합을 구축할 때 참조 역할을 할 수 있습니다.
빠른 API 참조
섹션 제목: “빠른 API 참조”interface AstroIntegration { name: string; hooks: { 'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build' | 'preview' | 'sync'; isRestart: boolean; updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; addRenderer: (renderer: AstroRenderer) => void; addWatchFile: (path: URL | string) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: (injectedRoute: InjectedRoute) => void; createCodegenDir: () => URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:route:setup'?: (options: { route: RouteOptions; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:routes:resolved'?: (options: { routes: IntegrationResolvedRoute[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:config:done'?: (options: { config: AstroConfig; setAdapter: (adapter: AstroAdapter) => void; injectTypes: (injectedType: InjectedType) => URL; logger: AstroIntegrationLogger; buildOutput: 'static' | 'server'; }) => void | Promise<void>; 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; refreshContent?: (options: RefreshContentOptions) => Promise<void>; }) => void | Promise<void>; 'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:server:done'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:start'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:setup'?: (options: { vite: vite.InlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: vite.InlineConfig) => void; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; entryPoints: Map<IntegrationRouteData, URL>; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; assets: Map<string, URL[]>; logger: AstroIntegrationLogger; }) => void | Promise<void>;
// ... 통합의 모든 사용자 정의 훅 };}Astro는 통합 기능이 Astro의 라이프사이클의 특정 부분 동안 실행할 수 있도록 구현할 수 있는 훅을 제공합니다. Astro 훅은 전역 Astro 네임스페이스의 일부인 IntegrationHooks 인터페이스에 정의되어 있습니다. 각 훅에는 Astro 로거를 사용하여 로그를 작성할 수 있도록 하는 logger 옵션이 있습니다.
다음 훅은 Astro에 내장되어 있습니다.
astro:config:setup
섹션 제목: “astro:config:setup”다음 훅: astro:route:setup
실행 시점: 초기화 시, Vite 또는 Astro 구성이 결정되기 전.
사용 목적: 프로젝트 구성을 확장합니다. 여기에는 Astro 구성 업데이트, Vite 플러그인 적용, 컴포넌트 렌더러 추가 및 페이지에 스크립트 삽입이 포함됩니다.
'astro:config:setup'?: (options: { config: AstroConfig; command: 'dev' | 'build' | 'preview' | 'sync'; isRestart: boolean; updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; addRenderer: (renderer: AstroRenderer) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; addMiddleware: (middleware: AstroIntegrationMiddleware) => void; addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void; addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: (injectedRoute: InjectedRoute) => void; createCodegenDir: () => URL; logger: AstroIntegrationLogger;}) => void | Promise<void>;config 옵션
섹션 제목: “config 옵션”타입: AstroConfig
사용자가 제공한 Astro 구성의 읽기 전용 복사본입니다. 이는 다른 통합 기능이 실행되기 전에 결정됩니다. 모든 통합 기능이 구성 업데이트를 완료한 후의 구성 복사본이 필요한 경우 astro:config:done 훅을 참조하세요.
command 옵션
섹션 제목: “command 옵션”타입: 'dev' | 'build' | 'preview' | 'sync'
dev- 프로젝트가astro dev로 실행됩니다.build- 프로젝트가astro build로 실행됩니다.preview- 프로젝트가astro preview로 실행됩니다.sync- 프로젝트가astro sync로 실행됩니다.
isRestart 옵션
섹션 제목: “isRestart 옵션”타입: boolean
astro@1.5.0
개발 서버가 시작될 때 false, 다시 로드가 트리거될 때 true입니다. 이 함수가 두 번 이상 호출되는 시점을 감지하는 데 유용합니다.
updateConfig() 옵션
섹션 제목: “updateConfig() 옵션”타입: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
사용자가 제공한 Astro 구성을 업데이트하는 콜백 함수입니다. 제공하는 모든 구성은 사용자 구성 + 다른 통합 구성 업데이트와 병합되므로 키를 자유롭게 생략할 수 있습니다!
예를 들어, 사용자 프로젝트에 Vite 플러그인을 제공해야 한다고 가정해 봅시다.
import bananaCSS from '@vitejs/official-banana-css-plugin';
export default { name: 'banana-css-integration', hooks: { 'astro:config:setup': ({ updateConfig }) => { updateConfig({ vite: { plugins: [bananaCSS()], } }) } }}addRenderer() 옵션
섹션 제목: “addRenderer() 옵션”타입: (renderer: AstroRenderer) => void;
예: svelte, react, preact, vue, solid
컴포넌트 프레임워크 렌더러(예: React, Vue, Svelte 등)를 추가하는 콜백 함수입니다. 위 예시와 타입 정의에서 고급 옵션을 찾아볼 수 있지만, 알아야 할 두 가지 주요 옵션은 다음과 같습니다.
clientEntrypoint- 컴포넌트가 사용될 때마다 클라이언트에서 실행되는 파일의 경로입니다. 이는 주로 컴포넌트를 JS로 렌더링하거나 하이드레이팅하기 위한 것입니다.serverEntrypoint- 컴포넌트가 사용될 때마다 서버 측 요청 또는 정적 빌드 중에 실행되는 파일의 경로입니다. 이 파일들은 컴포넌트를 정적 마크업으로 렌더링해야 하며, 필요한 경우 하이드레이션을 위한 훅을 포함해야 합니다. React의renderToString콜백이 대표적인 예입니다.
추가된 버전:
astro@5.0.0
clientEntrypoint 및 serverEntrypoint 함수는 URL을 허용합니다.
addWatchFile() 옵션
섹션 제목: “addWatchFile() 옵션”타입: (path: URL | string) => void
astro@1.5.0
통합 기능이 Vite가 감시하지 않는 일부 구성 파일에 의존하거나 적용하기 위해 전체 개발 서버를 다시 시작해야 하는 경우 addWatchFile()을 사용하여 해당 파일을 추가합니다. 해당 파일이 변경될 때마다 Astro 개발 서버가 다시 로드됩니다 (isRestart를 사용하여 다시 로드가 발생하는 시점을 확인할 수 있습니다).
사용 예시:
// 반드시 절대 경로여야 합니다!addWatchFile('/home/user/.../my-config.json');addWatchFile(new URL('./ec.config.mjs', config.root));addClientDirective() 옵션
섹션 제목: “addClientDirective() 옵션”타입: (directive: ClientDirectiveConfig) => void;
astro@2.6.0
.astro 파일에서 사용할 사용자 정의 클라이언트 지시어를 추가합니다.
지시어 진입점은 esbuild를 통해서만 번들링되며, 컴포넌트 하이드레이션을 느리게 하지 않도록 작게 유지해야 합니다.
사용 예시:
import { defineConfig } from 'astro/config';import clickDirective from './astro-click-directive/register.js'
// https://astro.build/configexport default defineConfig({ integrations: [ clickDirective() ],});/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "client:click", hooks: { "astro:config:setup": ({ addClientDirective }) => { addClientDirective({ name: "click", entrypoint: "./astro-click-directive/click.js", }); }, },});/** * 첫 클릭 시 하이드레이션 * @type {import('astro').ClientDirective} */export default (load, opts, el) => { window.addEventListener('click', async () => { const hydrate = await load() await hydrate() }, { once: true })}라이브러리의 타입 정의 파일에서 지시어에 대한 타입을 추가할 수도 있습니다.
import 'astro'declare module 'astro' { interface AstroClientDirectives { 'client:click'?: boolean }}addDevToolbarApp() 옵션
섹션 제목: “addDevToolbarApp() 옵션”타입: (entrypoint: DevToolbarAppEntry) => void;
astro@3.4.0
사용자 정의 개발 툴바 앱을 추가합니다.
사용 예시:
import { defineConfig } from 'astro/config';import devToolbarIntegration from './astro-dev-toolbar-app/integration.js'
// https://astro.build/configexport default defineConfig({ integrations: [ devToolbarIntegration() ],});/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "dev-toolbar-app", hooks: { "astro:config:setup": ({ addDevToolbarApp }) => { addDevToolbarApp({ entrypoint: "./astro-dev-toolbar-app/plugin.js", id: "my-plugin", name: "My Plugin" }); }, },});/** * @type {import('astro').DevToolbarApp} */export default { id: "my-plugin", name: "My Plugin", icon: "<svg>...</svg>", init() { console.log("I'm a dev toolbar app!") },};addMiddleware() 옵션
섹션 제목: “addMiddleware() 옵션”타입: (middleware: AstroIntegrationMiddleware) => void;
astro@3.5.0
각 요청에서 실행할 미들웨어를 추가합니다. 미들웨어를 포함하는 entrypoint 모듈과 다른 미들웨어 전(pre)에 실행할지 후(post)에 실행할지를 지정하는 order를 사용합니다.
/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-middleware-package", hooks: { "astro:config:setup": ({ addMiddleware }) => { addMiddleware({ entrypoint: '@my-package/middleware', order: 'pre' }); }, },});미들웨어는 사용자 정의 미들웨어와 마찬가지로 onRequest() 함수 함수가 포함된 패키지에 정의됩니다.
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => { if(context.url.pathname === '/some-test-path') { return Response.json({ ok: true }); }
return next();});
추가된 버전:
astro@5.0.0
이 함수는 entrypoint에 URL도 허용합니다.
/** * @type {() => import('astro').AstroIntegration} */export default () => ({ name: "my-middleware-package", hooks: { "astro:config:setup": ({ addMiddleware }) => { addMiddleware({ entrypoint: new URL('./middleware.js', import.meta.url), order: 'pre' }); }, },});injectRoute() 옵션
섹션 제목: “injectRoute() 옵션”타입: ({ pattern: string; entrypoint: string | URL; prerender?: boolean }) => void;
Astro 프로젝트에 경로를 삽입하는 콜백 함수입니다. 삽입된 경로는 .astro 페이지 또는 .js 및 .ts 경로 핸들러일 수 있습니다.
injectRoute()는 pattern과 entrypoint가 포함된 객체를 전달받습니다.
pattern- 브라우저에서 경로가 출력되는 위치입니다(예:/foo/bar).pattern은/foo/[bar]또는/foo/[...bar]와 같이 동적 경로를 나타내기 위해 Astro의 파일 경로 구문을 사용할 수 있습니다.pattern에는 파일 확장자가 필요하지 않습니다.entrypoint-pattern에 표시된 경로를 처리하는.astro페이지 또는.js/.ts경로 핸들러를 가리키는 모듈 지정자입니다.prerender- Astro가prerender내보내기를 감지할 수 없는 경우 설정하는 부울 값입니다.
사용 예시
섹션 제목: “사용 예시”injectRoute({ // 동적 경로에 Astro의 패턴 구문을 사용합니다. pattern: '/subfolder/[dynamic]', // 로컬 경로에 상대 경로 구문을 사용합니다. entrypoint: './src/dynamic-page.astro', // Astro가 prerender 내보내기를 감지할 수 없는 경우에만 사용합니다. prerender: false});다른 프로젝트에 설치하도록 설계된 통합 기능의 경우, 해당 패키지 이름을 경로 진입점으로 참조합니다.
다음 예는 npm에 @fancy/dashboard로 게시된 패키지가 대시보드 경로를 삽입하는 방법을 보여줍니다.
injectRoute({ pattern: '/fancy-dashboard', entrypoint: '@fancy/dashboard/dashboard.astro'});npm에 패키지(@fancy/dashboard)를 게시할 때 package.json에서 dashboard.astro를 내보내야 합니다.
{ "name": "@fancy/dashboard", // ... "exports": { "./dashboard.astro": "./dashboard.astro" }}
추가된 버전:
astro@5.0.0
이 함수는 entrypoint에 URL도 허용합니다.
injectRoute({ pattern: '/fancy-dashboard', entrypoint: new URL('./dashboard.astro', import.meta.url)});injectScript() 옵션
섹션 제목: “injectScript() 옵션”타입: (stage: InjectedScriptStage, content: string) => void;
JavaScript 콘텐츠 문자열을 모든 페이지에 삽입하는 콜백 함수입니다.
stage 는 이 스크립트(content)가 어떻게 삽입되어야 하는지 나타냅니다. 일부 단계에서는 수정 없이 스크립트 삽입을 허용하는 반면 다른 단계에서는 Vite의 번들링 단계 중에 최적화를 허용합니다.
-
"head-inline": 모든 페이지의<head>에 있는 스크립트 태그에 삽입됩니다. Vite에서 최적화되거나 해결되지 않습니다. -
"before-hydration": 하이드레이션 스크립트가 실행되기 전에 클라이언트 측에서 가져옵니다. Vite에서 최적화되고 해결됩니다. -
"page": 삽입된 스니펫이 Vite에서 처리되고 페이지의 Astro 컴포넌트 내부에 정의된 다른<script>태그와 함께 번들된다는 점을 제외하고는head-inline과 유사합니다. 스크립트는 최종 페이지 출력에서<script type="module">과 함께 로드되며 Vite에서 최적화되고 해결됩니다. -
"page-ssr": 모든 Astro 페이지 컴포넌트의 프런트매터에서 별도의 모듈로 가져옵니다. 이 단계에서는 스크립트를 가져오기 때문에Astro전역 변수를 사용할 수 없으며 스크립트는import가 처음 평가될 때 한 번만 실행됩니다.page-ssr단계의 주요 용도는 모든 페이지에 CSSimport를 삽입하여 Vite에서 최적화하고 해결하는 것입니다.injectScript('page-ssr', 'import "global-styles.css";');
createCodegenDir
섹션 제목: “createCodegenDir”타입: () => URL;
astro@5.0.0
<root>/.astro/integrations/<normalized_integration_name> 폴더를 생성하고 해당 경로를 반환하는 함수입니다.
이를 통해 전용 폴더를 가질 수 있으므로 다른 통합 또는 Astro 자체와의 충돌을 피할 수 있습니다. 이 디렉터리는 이 함수를 호출하여 생성되므로 파일을 직접 작성해도 안전합니다.
import { writeFileSync } from 'node:fs'
const integration = { name: 'my-integration', hooks: { 'astro:config:setup': ({ createCodegenDir }) => { const codegenDir = createCodegenDir() writeFileSync(new URL('cache.json', codegenDir), '{}', 'utf-8') } }}astro:route:setup
섹션 제목: “astro:route:setup”
추가된 버전:
astro@4.14.0
이전 훅: astro:config:setup
다음 훅: astro:routes:resolved
실행 시점: astro build에서는 번들링이 시작되기 전에, astro dev에서는 모듈 그래프를 빌드하는 동안 및 파일 기반 라우트의 모든 변경 사항(추가/제거/업데이트)에 대해 실행됩니다.
사용 목적: 빌드 또는 요청 시에 온디맨드 서버 렌더링 활성화와 같은 라우트에 대한 옵션을 설정하기 위해.
'astro:route:setup'?: (options: { route: RouteOptions; logger: AstroIntegrationLogger;}) => void | Promise<void>;route 옵션
섹션 제목: “route 옵션”타입: { readonly component: string; prerender?: boolean; }
라우트를 식별하는 component 속성과 생성된 라우트를 구성할 수 있도록 하는 다음 추가 값(prerender)을 가진 객체입니다.
route.component
섹션 제목: “route.component”타입: string
astro@4.14.0
component 속성은 해당 라우트에서 렌더링될 진입점을 나타냅니다. 라우트가 빌드되기 전에 이 값에 접근하여 해당 페이지의 온디맨드 서버 렌더링을 구성할 수 있습니다.
route.prerender
섹션 제목: “route.prerender”타입: boolean
기본값: undefined
astro@4.14.0
prerender 속성은 라우트에 대한 온디맨드 서버 렌더링을 구성하는 데 사용됩니다. 라우트 파일에 명시적인 export const prerender 값이 포함되어 있으면 해당 값이 undefined 대신 기본값으로 사용됩니다.
import { defineConfig } from 'astro/config';
export default defineConfig({ integrations: [setPrerender()],});
function setPrerender() { return { name: 'set-prerender', hooks: { 'astro:route:setup': ({ route }) => { if (route.component.endsWith('/blog/[slug].astro')) { route.prerender = true; } }, }, };}모든 훅을 실행한 후 최종 값이 undefined이면, 라우트는 output 옵션에 따라 사전 렌더링 기본값으로 돌아갑니다. static 모드의 경우 사전 렌더링되고, server 모드의 경우 온디맨드 렌더링됩니다.
astro:routes:resolved
섹션 제목: “astro:routes:resolved”
추가된 버전:
astro@5.0.0
이전 훅: astro:route:setup
다음 훅: astro:config:done (설정 중에만)
실행 시점: astro dev에서는 파일 기반 라우트가 변경될 때마다(추가/삭제/업데이트) 실행됩니다.
사용 목적: 라우트와 해당 메타데이터에 접근하기 위해
'astro:routes:resolved'?: (options: { routes: IntegrationResolvedRoute[]; logger: AstroIntegrationLogger;}) => void | Promise<void>;routes 옵션
섹션 제목: “routes 옵션”타입: IntegrationResolvedRoute[]
연관된 메타데이터를 포함한 모든 라우트 목록입니다.
사용 예시:
const integration = () => { return { name: 'my-integration', hooks: { 'astro:routes:resolved': ({ routes }) => { const projectRoutes = routes.filter(r => r.origin === 'project').map(r => r.pattern)
console.log(projectRoutes) }, } }}astro:config:done
섹션 제목: “astro:config:done”이전 훅: astro:routes:resolved
다음 훅: “dev” 모드로 실행 중에는 astro:server:setup, 프로덕션 빌드 중에는 astro:build:start
실행 시점: Astro 구성이 해결되고 다른 통합이 astro:config:setup 훅을 실행한 후.
사용 목적: 다른 훅에서 사용하기 위해 최종 구성을 검색합니다.
'astro:config:done'?: (options: { config: AstroConfig; setAdapter: (adapter: AstroAdapter) => void; injectTypes: (injectedType: InjectedType) => URL; logger: AstroIntegrationLogger; buildOutput: 'static' | 'server';}) => void | Promise<void>;config 옵션
섹션 제목: “config 옵션”타입: AstroConfig
사용자가 제공한 Astro 구성의 읽기 전용 복사본입니다. 다른 통합이 실행된 후 해결됩니다.
setAdapter() 옵션
섹션 제목: “setAdapter() 옵션”타입: (adapter: AstroAdapter) => void;
통합을 어댑터로 만듭니다. 자세한 내용은 어댑터 API에서 확인하세요.
injectTypes() 옵션
섹션 제목: “injectTypes() 옵션”타입: (injectedType: { filename: string; content: string }) => URL
astro@4.14.0
새로운 *.d.ts 파일을 추가하여 사용자 프로젝트에 타입을 주입할 수 있습니다.
filename 속성은 /.astro/integrations/<normalized_integration_name>/<normalized_filename>.d.ts에 파일을 생성하는 데 사용되며 반드시 ".d.ts"로 끝나야 합니다.
content 속성은 파일 본문을 생성하며 유효한 TypeScript여야 합니다.
또한 injectTypes()는 정규화된 경로에 대한 URL을 반환하므로 나중에 해당 내용을 덮어쓰거나 원하는 방식으로 조작할 수 있습니다.
const path = injectTypes({ filename: "types.d.ts", content: "declare module 'virtual:integration' {}"})console.log(path) // URLbuildOutput 옵션
섹션 제목: “buildOutput 옵션”타입: 'static' | 'server'
astro@5.0.0
사용자 프로젝트 출력에 따라 통합의 논리를 조정할 수 있습니다.
astro:server:setup
섹션 제목: “astro:server:setup”이전 훅: astro:config:done
다음 훅: astro:server:start
실행 시점: “dev” 모드에서는 Vite 서버가 생성된 직후, listen() 이벤트가 발생하기 전에 실행됩니다. 자세한 내용은 Vite의 createServer API를 참조하세요.
사용 목적: Vite 서버 옵션 및 미들웨어를 업데이트하거나 콘텐츠 레이어 새로 고침 지원을 활성화하기 위해.
'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; refreshContent: (options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>;}) => void | Promise<void>;server 옵션
섹션 제목: “server 옵션”타입: ViteDevServer
“dev” 모드에서 사용되는 변경 가능한 Vite 서버 인스턴스입니다. 예를 들어, Partytown 통합에서 Partytown 서버를 미들웨어로 주입하는 데 사용됩니다.
export default { name: 'partytown', hooks: { 'astro:server:setup': ({ server }) => { server.middlewares.use( function middleware(req, res, next) { // 요청 처리 } ); } }}toolbar 옵션
섹션 제목: “toolbar 옵션”타입: ReturnType<typeof getToolbarServerCommunicationHelpers>
astro@4.7.0
개발 툴바와 상호 작용하는 콜백 함수를 제공하는 객체입니다.
on()
섹션 제목: “on()”타입: <T>(event: string, callback: (data: T) => void) => void
첫 번째 인자로 이벤트 이름, 두 번째 인자로 콜백 함수를 받는 함수입니다. 이를 통해 개발 툴바 앱에서 해당 이벤트와 관련된 데이터가 포함된 메시지를 받을 수 있습니다.
onAppInitialized()
섹션 제목: “onAppInitialized()”타입: (appId: string, callback: (data: Record<string, never>) => void) => void
개발 툴바 앱이 초기화될 때 실행되는 함수입니다. 첫 번째 인자는 초기화된 앱의 ID이고, 두 번째 인자는 앱이 초기화될 때 실행할 콜백 함수입니다.
onAppToggled()
섹션 제목: “onAppToggled()”타입: (appId: string, callback: (data: { state: boolean; }) => void) => void
개발 툴바 앱의 토글 상태가 변경될 때 실행되는 함수입니다. 첫 번째 인자는 토글된 앱의 ID이고, 두 번째 인자는 앱이 토글될 때 실행할 상태를 제공하는 콜백 함수입니다.
send()
섹션 제목: “send()”타입: <T>(event: string, payload: T) => void
앱이 수신 대기할 수 있는 메시지를 개발 툴바에 보내는 함수입니다. 첫 번째 인자로 이벤트 이름을, 두 번째 인자로 직렬화 가능한 모든 데이터인 페이로드를 받습니다.
refreshContent() 옵션
섹션 제목: “refreshContent() 옵션”타입: (options: { loaders?: Array<string>; context?: Record<string, any>; }) => Promise<void>
astro@5.0.0
astro dev 실행 중 통합 기능이 콘텐츠 레이어 업데이트를 트리거하는 함수입니다. 예를 들어, 개발 중 웹훅 엔드포인트를 등록하거나, 변경 사항을 수신하기 위해 CMS에 소켓을 열 때 사용할 수 있습니다.
기본적으로 refreshContent()는 모든 컬렉션을 새로 고칩니다. 선택적으로 로더 이름 배열인 loaders 속성을 전달할 수 있습니다. 제공된 경우 해당 로더를 사용하는 컬렉션만 새로 고쳐집니다. 예를 들어, CMS 통합 기능은 이 속성을 사용하여 자체 컬렉션만 새로 고칠 수 있습니다.
로더에 context 객체를 전달할 수도 있습니다. 이는 웹훅 본문이나 웹소켓의 이벤트와 같은 임의의 데이터를 전달하는 데 사용할 수 있습니다.
{ name: 'my-integration', hooks: { 'astro:server:setup': async ({ server, refreshContent }) => { // 개발 서버 웹훅 엔드포인트 등록 server.middlewares.use('/_refresh', async (req, res) => { if(req.method !== 'POST') { res.statusCode = 405 res.end('Method Not Allowed'); return } let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', async () => { try { const webhookBody = JSON.parse(body); await refreshContent({ context: { webhookBody }, loaders: ['my-loader'] }); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Content refreshed successfully' })); } catch (error) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Failed to refresh content: ' + error.message })); } }); }); } }}로더는 refreshContextData 속성에 접근하여 웹훅 본문을 가져올 수 있습니다. 자세한 내용은 refreshContextData 속성을 참조하세요.
astro:server:start
섹션 제목: “astro:server:start”이전 훅: astro:server:setup
다음 훅: astro:server:done
실행 시점: 서버의 listen() 이벤트가 발생한 직후.
사용 목적: 지정된 주소에서 네트워크 요청을 가로채기 위함입니다. 이 주소를 미들웨어에 사용하려면 대신 astro:server:setup을 사용하는 것이 좋습니다.
'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger;}) => void | Promise<void>;address 옵션
섹션 제목: “address 옵션”타입: AddressInfo
Node.js Net 모듈의 server.address() 메서드에서 제공하는 주소, 패밀리, 포트 번호입니다.
astro:server:done
섹션 제목: “astro:server:done”이전 훅: astro:server:start
실행 시점: 개발 서버가 닫힌 직후
사용 목적: astro:server:setup 또는 astro:server:start 훅 동안 트리거할 수 있는 정리 이벤트를 실행하기 위해
'astro:server:done'?: (options: { logger: AstroIntegrationLogger;}) => void | Promise<void>;astro:build:start
섹션 제목: “astro:build:start”이전 훅: astro:config:done
다음 훅: astro:build:setup
실행 시점: astro:config:done 이벤트 이후, 프로덕션 빌드가 시작되기 전.
사용 목적: 프로덕션 빌드 중에 필요한 전역 객체 또는 클라이언트를 설정하기 위함입니다. 또한 어댑터 API에서 빌드 구성 옵션을 확장할 수 있습니다.
'astro:build:start'?: (options: { logger: AstroIntegrationLogger;}) => void | Promise<void>;astro:build:setup
섹션 제목: “astro:build:setup”이전 훅: astro:build:start
다음 훅: astro:build:ssr
실행 시점: astro:build:start 훅 이후, 빌드 직전에 실행됩니다.
사용 목적: 이 시점에서 빌드에 대한 Vite 구성이 완전히 구성되었으므로, 이를 수정할 마지막 기회입니다. 예를 들어 일부 기본값을 덮어쓰는 데 유용할 수 있습니다. 이 훅을 사용해야 할지 astro:build:start를 사용해야 할지 확실하지 않은 경우 astro:build:start를 대신 사용하세요.
'astro:build:setup'?: (options: { vite: vite.InlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: vite.InlineConfig) => void; logger: AstroIntegrationLogger;}) => void | Promise<void>;vite 옵션
섹션 제목: “vite 옵션”타입: InlineConfig
빌드에 사용된 Vite 구성에 접근할 수 있는 객체입니다.
통합 기능에서 구성 옵션에 접근해야 하는 경우에 유용할 수 있습니다.
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ vite }) => { const { publicDir, root } = vite; }, }}pages 옵션
섹션 제목: “pages 옵션”타입: Map<string, PageBuildData>
키로 페이지 목록을, 값으로 해당 페이지의 빌드 데이터를 갖는 Map입니다.
이를 사용하여 특정 조건과 일치하는 경로가 있는 경우 작업을 수행할 수 있습니다.
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ pages }) => { pages.forEach((data) => { if (data.route.pattern.test("/blog")) { console.log(data.route.type); } }); }, }}페이지 빌드 데이터
섹션 제목: “페이지 빌드 데이터”페이지 빌드 방법을 설명하는 객체입니다.
key
섹션 제목: “key”타입: string
astro@4.8.0
페이지의 고유 식별자를 지정합니다.
component
섹션 제목: “component”타입: string
소스 컴포넌트 URL을 지정합니다.
route
섹션 제목: “route”타입: RouteData
페이지 라우트에 대한 정보를 설명합니다.
moduleSpecifier
섹션 제목: “moduleSpecifier”타입: string
모듈의 파일 경로로 해석될 수 있는 문자열을 정의합니다.
styles
섹션 제목: “styles”타입: Array<{ depth: number; order: number; sheet: { type: 'inline'; content: string } | { type: 'external'; src: string } }>
astro@2.4.0
페이지에 렌더링할 스타일 목록입니다. 각 스타일은 컴포넌트 트리에서의 depth와 페이지상의 표시 order를 포함하며, 이를 인라인 또는 외부 스타일로 적용해야 하는지에 대한 표시를 포함합니다.
target 옵션
섹션 제목: “target 옵션”타입: 'client' | 'server'
빌드는 client와 server 두 가지 개별 단계로 나뉩니다. 이 옵션을 사용하면 현재 빌드 단계를 확인할 수 있습니다.
이를 사용하여 특정 단계에서만 작업을 수행할 수 있습니다.
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ target }) => { if (target === "server") { // 서버 빌드 단계에서 수행될 작업 } }, }}updateConfig() 옵션
섹션 제목: “updateConfig() 옵션”타입: (newConfig: InlineConfig) => void
빌드에 사용되는 Vite 옵션을 업데이트하는 콜백 함수입니다. 제공하는 모든 구성은 사용자 구성 + 기타 통합 구성 업데이트와 병합되므로 키를 자유롭게 생략할 수 있습니다!
예를 들어, 사용자 프로젝트에 플러그인을 제공하는 데 사용할 수 있습니다.
import awesomeCssPlugin from 'awesome-css-vite-plugin';
export default { name: 'my-integration', hooks: { 'astro:build:setup': ({ updateConfig }) => { updateConfig({ plugins: [awesomeCssPlugin()], }) } }}astro:build:ssr
섹션 제목: “astro:build:ssr”이전 훅: astro:build:setup
다음 훅: astro:build:generated
실행 시점: 프로덕션 SSR 빌드가 완료된 후
사용 목적: SSR 매니페스트와 방출된 진입점의 맵에 접근하기 위함입니다. 플러그인이나 통합 기능에서 사용자 지정 SSR 빌드를 생성할 때 유용합니다.
entryPoints는 페이지 경로를 빌드 후 방출된 물리적 파일에 매핑합니다;middlewareEntryPoint는 미들웨어 파일의 파일 시스템 경로입니다;
'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest; entryPoints: Map<IntegrationRouteData, URL>; middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger;}) => void | Promise<void>;manifest 옵션
섹션 제목: “manifest 옵션”SSR 매니페스트에 액세스하여 커스텀 빌드를 생성할 수 있습니다.
export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ manifest }) => { const { i18n } = manifest; if (i18n?.strategy === "domains-prefix-always") { // 작업 수행 } }, },}직렬화된 SSR 매니페스트 속성
섹션 제목: “직렬화된 SSR 매니페스트 속성”astro:build:ssr 훅을 통해 접근할 수 있는 SSRManifest의 직렬화된 버전입니다. 이는 SSRManifest와 동일한 정보를 포함하며, 일부 속성은 직렬화 가능한 형식으로 변환됩니다.
routes
섹션 제목: “routes”타입: SerializedRouteInfo[]
직렬화된 라우트 정보 목록을 정의합니다. 각 라우트는 SSRManifest.routes와 동일한 속성을 포함하며, routeData는 JSON으로 직렬화 가능한 형식으로 변환됩니다.
assets
섹션 제목: “assets”타입: string[]
직렬화된 자산 파일 경로 목록을 정의합니다.
componentMetadata
섹션 제목: “componentMetadata”타입: [string, SSRComponentMetadata][]
astro@2.1.7
첫 번째 요소가 컴포넌트 식별자이고 두 번째 요소가 빌드 메타데이터를 설명하는 객체인 키-값 쌍의 배열을 정의합니다.
inlinedScripts
섹션 제목: “inlinedScripts”타입: [string, string][]
각 항목이 튜플인 키-값 쌍의 배열을 정의합니다. 첫 번째 요소는 스크립트 식별자이고 두 번째 요소는 스크립트 콘텐츠입니다.
clientDirectives
섹션 제목: “clientDirectives”타입: [string, string][]
astro@2.5.0
첫 번째 요소가 지시어 이름(예: load, visible)이고 두 번째 요소가 지시어의 구현 코드인 키-값 쌍의 배열을 정의합니다.
serverIslandNameMap
섹션 제목: “serverIslandNameMap”타입: [string, string][]
astro@4.12.0
각 항목이 튜플인 키-값 쌍의 배열을 정의합니다. 첫 번째 요소는 컴포넌트 경로이고 두 번째 요소는 할당된 이름입니다.
key
섹션 제목: “key”타입: string
astro@4.13.4
서버 아일랜드 props를 암호화하는 데 사용되는, 문자열로 직렬화된 암호화 키를 지정합니다.
entryPoints 옵션
섹션 제목: “entryPoints 옵션”타입: Map<IntegrationRouteData, URL>
astro@2.7.0
IntegrationRouteData를 키로, 물리적 파일 URL을 값으로 갖는 방출된 진입점의 Map입니다.
export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ entryPoints }) => { entryPoints.forEach((url) => { console.log(url.href); }); }, },}middlewareEntryPoint 옵션
섹션 제목: “middlewareEntryPoint 옵션”타입: URL | undefined
astro@2.8.0
미들웨어 파일 경로를 노출합니다.
export default { name: 'my-integration', hooks: { 'astro:build:ssr': ({ middlewareEntryPoint }) => { if (middlewareEntryPoint) { // 미들웨어가 존재하는 경우 작업 수행 } }, },}astro:build:generated
섹션 제목: “astro:build:generated”
추가된 버전:
astro@1.3.0
이전 훅: astro:build:ssr
다음 훅: astro:build:done
실행 시점: 정적 프로덕션 빌드가 경로 및 자산 생성을 완료한 후.
사용 목적: 빌드 결과물이 정리되기 전에 생성된 경로 및 자산에 접근하기 위함입니다. 매우 드문 사용 사례입니다. 정리 전에 생성된 파일에 접근해야 하는 경우가 아니면 astro:build:done을 사용하는 것이 좋습니다.
'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger;}) => void | Promise<void>;dir 옵션
섹션 제목: “dir 옵션”타입: URL
빌드 출력 디렉터리에 대한 URL 경로입니다.
다음 예시는 Node.js의 내장 fileURLToPath() 유틸리티를 사용하여 통합에서 제공하는 파일의 유효한 절대 경로 문자열을 계산합니다.
import { fileURLToPath } from 'node:url';
export default { name: 'my-integration', hooks: { 'astro:build:generated': ({ dir }) => { const outFile = fileURLToPath(new URL('./my-integration.json', dir)); } }}astro:build:done
섹션 제목: “astro:build:done”이전 훅: astro:build:generated
실행 시점: 프로덕션 빌드(SSG 또는 SSR)가 완료된 후.
사용 목적: 생성된 경로 및 자산에 접근하여 확장하기 위함입니다 (예: 생성된 /assets 디렉터리에 콘텐츠 복사). 생성된 자산을 변환하려는 경우 Vite 플러그인 API를 살펴보고 대신 astro:config:setup을 통해 구성하는 것이 좋습니다.
'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL; /** @deprecated Use the `assets` map and the new `astro:routes:resolved` hook */ routes: IntegrationRouteData[]; assets: Map<string, URL[]>; logger: AstroIntegrationLogger;}) => void | Promise<void>;dir 옵션
섹션 제목: “dir 옵션”타입: URL
빌드 출력 디렉터리에 대한 URL 경로입니다.
다음 예시는 Node.js의 내장 fileURLToPath() 유틸리티를 사용하여 파일에 쓰기 전, 통합에서 제공하는 파일의 유효한 절대 경로 문자열을 계산합니다.
import { writeFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';
export default function myIntegration() { return { hooks: { 'astro:build:done': async ({ dir }) => { const metadata = await getIntegrationMetadata(); // 유효한 크로스 플랫폼 절대 경로 문자열을 가져오려면 fileURLToPath를 사용합니다. const outFile = fileURLToPath(new URL('./my-integration.json', dir)); await writeFile(outFile, JSON.stringify(metadata)); } } }}routes 옵션
섹션 제목: “routes 옵션”이 속성은 v5.0부터 더 이상 사용되지 않습니다. 마이그레이션 가이드를 확인하세요.
생성된 모든 경로와 연결된 메타데이터 목록입니다.
아래에서 전체 IntegrationRouteData 타입을 참조할 수 있지만, 가장 일반적인 속성은 다음과 같습니다.
component- 프로젝트 루트를 기준으로 하는 입력 파일 경로pathname- 출력 파일 URL ([dynamic]및[...spread]매개변수를 사용하는 경로의 경우 undefined)
assets 옵션
섹션 제목: “assets 옵션”타입: Map<string, URL[]>
astro@5.0.0
IntegrationResolvedRoute pattern 속성별로 그룹화된 출력 파일 경로의 URL을 포함합니다.
pages 옵션
섹션 제목: “pages 옵션”타입: { pathname: string }[]
생성된 모든 페이지의 목록입니다. 각 항목은 하나의 속성을 가진 객체입니다.
pathname- 페이지의 최종 경로.
사용자 정의 훅
섹션 제목: “사용자 정의 훅”사용자 정의 훅은 전역 확장을 통해 IntegrationHooks 인터페이스를 확장하여 통합 기능에 추가할 수 있습니다.
declare global { namespace Astro { export interface IntegrationHook { 'your:hook': (params: YourHookParameters) => Promise<void> } }}Astro는 향후 내장 훅을 위해 astro: 접두사를 예약합니다. 사용자 정의 훅 이름을 지정할 때 다른 접두사를 선택하세요.
통합 타입 참조
섹션 제목: “통합 타입 참조”astro 모듈에서 다음 타입을 가져올 수 있습니다.
import type { AstroIntegrationLogger, AstroIntegrationMiddleware, AstroMiddlewareInstance, AstroRenderer, ClientDirectiveConfig, HookParameters, IntegrationResolvedRoute, RedirectConfig, RouteData, RoutePart, RouteType, SSRComponentMetadata, SSRLoadedRenderer, SSRLoadedRendererValue, SSRManifest, SSRManifestCSP, ValidRedirectStatus, // 다음 타입은 더 이상 사용되지 않습니다. IntegrationRouteData,} from "astro";AstroIntegrationLogger
섹션 제목: “AstroIntegrationLogger”로그를 작성하는 데 유용한 Astro 로거의 인스턴스입니다. 이 로거는 CLI를 통해 구성된 동일한 로그 수준을 사용합니다.
터미널에 쓰기 위해 사용 가능한 메서드:
logger.info("Message");logger.warn("Message");logger.error("Message");logger.debug("Message");
모든 메시지에는 통합 이름과 동일한 값을 가진 레이블이 접두사로 붙습니다.
import type { AstroIntegration } from "astro";export function formatIntegration(): AstroIntegration { return { name: "astro-format", hooks: { "astro:build:done": ({ logger }) => { // 작업 수행 logger.info("Integration ready."); } } }}위의 예제는 제공된 info 메시지를 포함하는 메시지를 기록합니다.
[astro-format] Integration ready.다른 레이블로 일부 메시지를 기록하려면 .fork 메서드를 사용하여 기본 name에 대한 대안을 지정합니다.
import type { AstroIntegration } from "astro";export function formatIntegration(): AstroIntegration { return { name: "astro-format", hooks: { "astro:config:done": ({ logger }) => { // 작업 수행 logger.info("Integration ready."); }, "astro:build:done": ({ logger }) => { const buildLogger = logger.fork("astro-format/build"); // 작업 수행 buildLogger.info("Build finished.") } } }}위의 예제는 기본적으로 [astro-format]으로 로그를 생성하고, 지정된 경우에는 [astro-format/build]로 로그를 생성합니다.
[astro-format] Integration ready.[astro-format/build] Build finished.AstroIntegrationMiddleware
섹션 제목: “AstroIntegrationMiddleware”타입: { order: "pre" | "post"; entrypoint: string | URL; }
통합에 의해 추가된 미들웨어를 설명합니다.
order
섹션 제목: “order”타입: "pre" | "post"
미들웨어가 다른 미들웨어보다 먼저(pre) 실행되어야 할지 아니면 이후(post)에 실행되어야 할지를 지정합니다.
entrypoint
섹션 제목: “entrypoint”타입: string | URL
미들웨어의 가져오기 경로를 정의합니다.
AstroMiddlewareInstance
섹션 제목: “AstroMiddlewareInstance”타입: { onRequest?: MiddlewareHandler; }
프로젝트의 미들웨어 함수가 존재하는 경우, 해당 함수로 정의된 onRequest() 속성을 포함하는 객체입니다.
AstroRenderer
섹션 제목: “AstroRenderer”타입: { name: string; clientEntrypoint?: string | URL; serverEntrypoint: string | URL; }
통합에 의해 추가된 컴포넌트 프레임워크 렌더러를 설명합니다.
name
섹션 제목: “name”타입: string
컴포넌트 프레임워크 렌더러의 이름입니다.
clientEntrypoint
섹션 제목: “clientEntrypoint”타입: string | URL
컴포넌트가 사용될 때마다 클라이언트에서 실행되는 렌더러의 가져오기 경로를 정의합니다.
serverEntrypoint
섹션 제목: “serverEntrypoint”타입: string | URL
컴포넌트가 사용될 때마다 서버 측 요청 또는 정적 빌드 중에 실행되는 렌더러의 가져오기 경로를 정의합니다.
ClientDirectiveConfig
섹션 제목: “ClientDirectiveConfig”타입: { name: string; entrypoint: string | URL; }
통합에 의해 추가된 사용자 정의 클라이언트 지시어를 설명합니다.
name
섹션 제목: “name”타입: string
지시어에 의해 트리거되는 이벤트의 사용자 정의 이름입니다.
entrypoint
섹션 제목: “entrypoint”타입: string | URL
지시어가 사용될 때마다 실행되는 코드의 가져오기 경로를 정의합니다.
HookParameters
섹션 제목: “HookParameters”HookParameters 유틸리티 타입에 훅의 이름을 전달하여 훅 인자의 타입을 가져올 수 있습니다.
다음 예시에서 함수의 options 인자는 astro:config:setup 훅의 매개변수와 일치하도록 타입이 지정되었습니다.
import type { HookParameters } from 'astro';
function mySetup(options: HookParameters<'astro:config:setup'>) { options.updateConfig({ /* ... */ });}IntegrationResolvedRoute
섹션 제목: “IntegrationResolvedRoute”속성이 다시 매핑된 RouteData의 하위 집합입니다.
interface IntegrationResolvedRoute extends Pick< RouteData, 'generate' | 'params' | 'pathname' | 'segments' | 'type' | 'redirect' | 'origin' > & { pattern: RouteData['route']; patternRegex: RouteData['pattern']; entrypoint: RouteData['component']; isPrerendered: RouteData['prerender']; redirectRoute?: IntegrationResolvedRoute;}pattern
섹션 제목: “pattern”경로를 기반으로 경로의 타입을 식별할 수 있습니다. 다음은 패턴과 연결된 경로의 몇 가지 예입니다.
src/pages/index.astro는/가 됩니다.src/pages/blog/[...slug].astro는/blog/[...slug]가 됩니다.src/pages/site/[blog]/[...slug].astro는/site/[blog]/[...slug]가 됩니다.
patternRegex
섹션 제목: “patternRegex”입력 URL을 요청된 경로와 매치하는 데 사용되는 정규식에 접근할 수 있습니다.
예를 들어, [fruit]/about.astro 경로가 주어지면 정규식은 /^\/([^/]+?)\/about\/?$/가 됩니다. pattern.test("banana/about")을 사용하면 true가 반환됩니다.
entrypoint
섹션 제목: “entrypoint”소스 컴포넌트의 URL 경로 이름입니다.
isPrerendered
섹션 제목: “isPrerendered”경로가 온디맨드 렌더링을 사용하는지 여부를 결정합니다. 이 값은 다음과 같이 구성된 프로젝트의 경우 true가 됩니다.
- 경로가
const prerender = true를 내보내지 않을 때output: 'static' - 경로가
const prerender = false를 내보낼 때output: 'server'
redirectRoute
섹션 제목: “redirectRoute”타입: IntegrationResolvedRoute | undefined
IntegrationResolvedRoute.type의 값이 redirect인 경우, 값은 리디렉션할 IntegrationResolvedRoute가 됩니다. 그렇지 않으면 값은 undefined가 됩니다.
RedirectConfig
섹션 제목: “RedirectConfig”타입: string | { status: ValidRedirectStatus; destination: string; }
리디렉션의 목적지를 설명합니다. 문자열이거나 상태 코드와 목적지에 대한 정보를 포함하는 객체일 수 있습니다.
RouteData
섹션 제목: “RouteData”라우트에 대한 정보를 설명합니다.
route
섹션 제목: “route”타입: string
현재 라우트 패턴을 정의합니다. 다음은 패턴과 연관된 경로의 몇 가지 예시입니다.
src/pages/index.astro는/가 됩니다.src/pages/blog/[...slug].astro는/blog/[...slug]가 됩니다.src/pages/site/[blog]/[...slug].astro는/site/[blog]/[...slug]가 됩니다.
component
섹션 제목: “component”타입: string
소스 컴포넌트 URL을 지정합니다.
generate()
섹션 제목: “generate()”타입: (data?: any) => string
경로의 선택적 매개변수를 제공하고, 경로 패턴과 함께 보간하여 경로의 이름을 반환하는 함수입니다.
예를 들어, /blog/[...id].astro와 같은 경로를 사용하면 generate() 함수는 다음을 반환할 수 있습니다.
generate({ id: 'presentation' }) // `/blog/presentation`을 출력합니다.params
섹션 제목: “params”타입: string[]
경로 params에 접근할 수 있습니다. 예를 들어, 프로젝트에서 /pages/[lang]/[...slug].astro와 같은 동적 경로를 사용하는 경우 값은 ['lang', '...slug']가 됩니다.
pathname
섹션 제목: “pathname”타입: string | undefined
일반 경로의 경우, 값은 이 경로가 제공될 URL 경로 이름이 됩니다. 프로젝트에서 동적 경로(예: [dynamic] 또는 [...spread])를 사용하는 경우 경로 이름은 undefined가 됩니다.
distURL
섹션 제목: “distURL”타입: URL[] | undefined
astro@5.0.0
이 라우트에서 생성된 실제 파일의 경로를 정의합니다. 라우트가 미리 렌더링되지 않은 경우 값은 undefined이거나 빈 배열입니다.
pattern
섹션 제목: “pattern”타입: RegExp
입력된 URL을 요청된 라우트와 일치시키는 데 사용할 정규식을 지정합니다.
예를 들어, [fruit]/about.astro 경로가 주어지면 정규식은 /^\/([^/]+?)\/about\/?$/가 됩니다. pattern.test("banana/about")을 사용하면 true가 반환됩니다.
segments
섹션 제목: “segments”타입: RoutePart[][]
추가 메타데이터와 함께 경로 params에 접근할 수 있습니다. 각 객체는 다음 속성을 포함합니다.
content:param이름dynamic: 경로가 동적인지 여부spread: 동적 경로가 spread 구문을 사용하는지 여부
예를 들어, 경로 /pages/[blog]/[...slug].astro는 다음 세그먼트를 출력합니다.
[ [ { content: 'pages', dynamic: false, spread: false } ], [ { content: 'blog', dynamic: true, spread: false } ], [ { content: '...slug', dynamic: true, spread: true } ]]type
섹션 제목: “type”타입: RouteType
라우트의 타입을 식별할 수 있습니다.
prerender
섹션 제목: “prerender”타입: boolean
라우트가 온디맨드 렌더링을 사용할지 또는 빌드 시점에 정적으로 사전 렌더링할지 여부를 결정합니다.
라우팅 참조에서 prerendered를 확인하세요.
redirect
섹션 제목: “redirect”타입: RedirectConfig | undefined
리디렉션할 라우트에 액세스할 수 있습니다.
redirectRoute
섹션 제목: “redirectRoute”타입: RouteData | undefined
RouteData.type가 redirect일 때 리디렉션할 RouteData를 지정합니다.
fallbackRoutes
섹션 제목: “fallbackRoutes”타입: RouteData[]
astro@3.5.6
i18n.fallback에 로케일 목록이 지정되어 있을 때, 대체로 사용할 RouteData 목록을 정의합니다.
isIndex
섹션 제목: “isIndex”타입: boolean
해당 라우트가 디렉터리 인덱스인지 여부를 지정합니다. (예: src/pages/index.astro, src/pages/blog/index.astro)
origin
섹션 제목: “origin”타입: 'internal' | 'external' | 'project'
astro@5.0.0
해당 라우트가 Astro 코어(internal), 통합 기능(external), 또는 사용자 프로젝트(project)에서 비롯된 것인지 결정합니다.
RoutePart
섹션 제목: “RoutePart”타입: { content: string; dynamic: boolean; spread: boolean; }
라우트 세그먼트를 설명합니다.
content
섹션 제목: “content”타입: string
라우트의 매개변수 이름을 지정합니다. 예를 들면 다음과 같습니다.
about.astro의 이름은about입니다.[slug].astro의 이름은slug입니다.[...id].astro의 이름은id입니다.
dynamic
섹션 제목: “dynamic”타입: boolean
해당 라우트가 동적인지 여부를 나타냅니다.
spread
섹션 제목: “spread”타입: boolean
동적 라우트가 스프레드 문법을 사용하는지 여부를 나타냅니다.
RouteType
섹션 제목: “RouteType”타입: 'page' | 'endpoint' | 'redirect' | 'fallback'
지원되는 라우트 타입들의 유니언입니다.
page: 파일 시스템에 존재하는 라우트로, 일반적으로 Astro 컴포넌트입니다.endpoint: 파일 시스템에 존재하는 라우트로, 일반적으로 엔드포인트 메서드를 노출하는 JS 파일입니다.redirect: 파일 시스템에 존재하는 다른 라우트를 가리키는 라우트입니다.fallback: 파일 시스템에는 존재하지 않으며, 보통 미들웨어 등 다른 방식으로 처리해야 하는 라우트입니다.
SSRComponentMetadata
섹션 제목: “SSRComponentMetadata”타입: { propagation: PropagationHint; containsHead: boolean; }
서버에서 렌더링된 컴포넌트의 빌드 메타데이터를 설명합니다.
propagation
섹션 제목: “propagation”타입: 'none' | 'self' | 'in-tree'
이 컴포넌트에서 head 콘텐츠를 렌더링하는 방법에 대한 설명이며, Astro 런타임이 다음 컴포넌트를 기다려야 하는지 여부를 포함합니다.
none: 컴포넌트가 head 콘텐츠를 전파하지 않습니다.self: 컴포넌트가 head 콘텐츠를 추가합니다.in-tree: 이 컴포넌트의 의존성 트리에 있는 다른 컴포넌트가 head 콘텐츠를 추가합니다.
containsHead
섹션 제목: “containsHead”타입: boolean
컴포넌트가 head 콘텐츠를 포함하는지 여부를 결정합니다.
SSRLoadedRenderer
섹션 제목: “SSRLoadedRenderer”타입: { name: string; clientEntrypoint?: string | URL; ssr: SSRLoadedRendererValue; }
서버에서 사용할 수 있는 렌더러를 설명합니다. 이는 AstroRenderer의 하위 집합이며 다음과 같은 추가 속성을 포함합니다.
ssr
섹션 제목: “ssr”이 프레임워크를 위해 서버에서 사용하는 함수 및 설정을 정의합니다.
SSRLoadedRendererValue
섹션 제목: “SSRLoadedRendererValue”특정 UI 프레임워크의 컴포넌트를 서버에서 렌더링하는 데 필요한 함수와 설정을 포함합니다.
name
섹션 제목: “name”타입: string
렌더러의 이름 식별자를 지정합니다.
check()
섹션 제목: “check()”타입: AsyncRendererComponentFn<boolean>
렌더러가 해당 컴포넌트를 처리해야 할지 여부를 결정합니다.
renderToStaticMarkup()
섹션 제목: “renderToStaticMarkup()”타입: AsyncRendererComponentFn<{ html: string; attrs?: Record<string, string>; }>
프레임워크 컴포넌트를 서버에서 정적 HTML 마크업으로 렌더링합니다.
supportsAstroStaticSlot
섹션 제목: “supportsAstroStaticSlot”타입: boolean
astro@2.5.0
렌더러가 Astro의 정적 슬롯 최적화를 지원하는지 여부를 나타냅니다. 이 값이 true이면, Astro는 아일랜드 내부에 중첩된 슬롯이 제거되지 않도록 방지합니다.
renderHydrationScript()
섹션 제목: “renderHydrationScript()”타입: () => string
astro@4.1.0
첫 번째 컴포넌트가 이 렌더러를 사용하기 전, HTML에 주입되어야 하는 프레임워크별 하이드레이션 스크립트를 반환합니다.
SSRManifest
섹션 제목: “SSRManifest”서버 어댑터가 요청 시 렌더링되는 페이지를 서비스하기 위해 런타임에 사용하는 빌드 설정 및 프로젝트 메타데이터를 포함하는 객체입니다.
hrefRoot
섹션 제목: “hrefRoot”타입: string
astro@4.12.0
URL을 생성하는 데 사용되는 루트 경로를 지정합니다.
adapterName
섹션 제목: “adapterName”타입: string
요청 시 렌더링에 사용되는 서버 어댑터의 이름을 정의합니다.
routes
섹션 제목: “routes”타입: RouteInfo[]
이 프로젝트에서 사용 가능한 라우트에 대한 정보 목록입니다. 각 항목은 다음 속성들을 포함합니다.
routeData
섹션 제목: “routeData”타입: RouteData
라우트에 대해 알려진 정보를 설명하는 객체입니다.
file
섹션 제목: “file”타입: string
빌드된 라우트 진입점의 파일 경로를 지정합니다.
links
섹션 제목: “links”타입: string[]
이 라우트에 필요한 HTML link 요소 목록을 정의합니다.
scripts
섹션 제목: “scripts”타입: Array<{ children: string; stage: string } | { type: 'inline' | 'external'; value: string }>
이 라우트와 관련된 스크립트 목록을 정의합니다. 여기에는 children 및 stage 속성을 가진 통합 삽입 스크립트와 type 및 value 속성을 가진 호이스팅된 스크립트가 모두 포함됩니다.
styles
섹션 제목: “styles”타입: Array<{ type: "inline"; content: string; } | { type: "external"; src: string; }>
astro@2.4.0
이 라우트와 관련된 스타일시트 목록을 정의합니다. 여기에는 인라인 스타일과 스타일시트 URL이 모두 포함됩니다.
site
섹션 제목: “site”타입: string
설정된 site를 지정합니다.
base
섹션 제목: “base”타입: string
배포할 설정된 base 경로를 지정합니다.
userAssetsBase
섹션 제목: “userAssetsBase”타입: string | undefined
astro@5.3.1
스크립트 및 스타일과 같은 사용자가 생성한 자산에 대해 개발 모드에서 사용할 기본 경로를 지정합니다.
trailingSlash
섹션 제목: “trailingSlash”타입: AstroConfig['trailingSlash']
astro@3.5.4
개발 모드 및 요청 시 렌더링된 페이지에 대해 설정된 트레일링 슬래시 동작을 지정합니다.
buildFormat
섹션 제목: “buildFormat”타입: NonNullable<AstroConfig['build']>['format']
astro@4.2.2
설정된 출력 파일 형식을 지정합니다.
compressHTML
섹션 제목: “compressHTML”타입: boolean
astro@2.7.2
프로젝트 구성에서 HTML 축소가 활성화되어 있는지 여부를 결정합니다.
assetsPrefix
섹션 제목: “assetsPrefix”타입: string | ({ fallback: string; } & Record<string, string>) | undefined
astro@2.3.1
Astro가 생성한 자산 링크에 대해 설정된 접두사를 지정합니다.
renderers
섹션 제목: “renderers”타입: SSRLoadedRenderer[]
서버에서 사용할 수 있는 렌더러(예: React, Vue, Svelte, MDX)의 목록입니다.
clientDirectives
섹션 제목: “clientDirectives”타입: Map<string, string>
astro@2.5.0
클라이언트 지시어 이름(예: load, visible)을 해당 구현 코드에 매핑하여 정의합니다. 여기에는 기본 제공 클라이언트 지시어와 사용자 정의 클라이언트 지시어가 모두 포함됩니다.
entryModules
섹션 제목: “entryModules”타입: Record<string, string>
진입점과 해당 출력 파일 경로 간의 매핑을 정의합니다.
inlinedScripts
섹션 제목: “inlinedScripts”타입: Map<string, string>
astro@4.5.0
HTML 출력에 인라인으로 포함될 스크립트의 식별자와 해당 콘텐츠 간의 매핑을 정의합니다.
assets
섹션 제목: “assets”타입: Set<string>
빌드에 포함된 모든 자산의 파일 경로 세트를 정의합니다.
componentMetadata
섹션 제목: “componentMetadata”타입: Map<string, SSRComponentMetadata>
astro@2.1.7
컴포넌트 식별자와 빌드 메타데이터 간의 매핑을 정의합니다. 각 항목에는 propagation 동작 및 헤드 요소 포함 여부에 대한 정보가 포함됩니다.
pageModule
섹션 제목: “pageModule”타입: { page: ImportComponentInstance; onRequest?: MiddlewareHandler; renderers: SSRLoadedRenderer[]; }
astro@2.7.0
페이지 모듈에 대한 정보를 지정합니다.
page()
섹션 제목: “page()”타입: () => Promise<ComponentInstance>
페이지 컴포넌트의 인스턴스를 가져오는 함수입니다.
onRequest()
섹션 제목: “onRequest()”astro@3.0.3
사용자 프로젝트에 정의된 Astro 미들웨어 함수입니다.
renderers
섹션 제목: “renderers”타입: SSRLoadedRenderer[]
서버가 이 페이지에서 사용할 수 있는 렌더러 목록입니다.
pageMap
섹션 제목: “pageMap”타입: Map<string, () => Promise<typeof pageModule>>
컴포넌트 경로와 가져오기 가능한 인스턴스 간의 매핑을 정의합니다.
serverIslandMap
섹션 제목: “serverIslandMap”타입: Map<string, () => Promise<ComponentInstance>>
astro@4.12.0
서버 아일랜드 ID와 컴포넌트 인스턴스 간의 매핑을 정의합니다.
serverIslandNameMap
섹션 제목: “serverIslandNameMap”타입: Map<string, string>
astro@4.12.0
서버 아일랜드 컴포넌트 경로와 할당된 이름 간의 매핑을 정의합니다.
key
섹션 제목: “key”타입: Promise<CryptoKey>
astro@4.13.4
서버 아일랜드 props를 암호화하는 데 사용되는 암호화 키를 결정합니다.
i18n
섹션 제목: “i18n”타입: SSRManifestI18n | undefined
astro@3.5.0
프로젝트에서 활성화된 경우 해결된 i18n 구성을 지정합니다.
strategy
섹션 제목: “strategy”타입: "manual" | "pathname-prefix-always" | "pathname-prefix-other-locales" | "pathname-prefix-always-no-redirect" | "domains-prefix-always" | "domains-prefix-other-locales" | "domains-prefix-always-no-redirect"
설정된 i18n 라우팅 전략을 정의합니다. 이는 URL에서 로케일이 처리되는 방식과 리디렉션 발생 여부를 결정합니다.
locales
섹션 제목: “locales”타입: Locales
프로젝트에 설정된 지원되는 로케일 목록을 지정합니다.
defaultLocale
섹션 제목: “defaultLocale”타입: string
프로젝트에 설정된 기본 로케일을 결정합니다.
fallback
섹션 제목: “fallback”타입: Record<string, string> | undefined
로케일과 i18n.fallback에 설정된 대체 로케일 간의 매핑을 지정합니다.
fallbackType
섹션 제목: “fallbackType”타입: "redirect" | "rewrite"
프로젝트에 설정된 대체 전략을 결정합니다.
domainLookupTable
섹션 제목: “domainLookupTable”타입: Record<string, string>
설정된 도메인과 관련 로케일 간의 매핑입니다.
middleware
섹션 제목: “middleware”타입: () => Promise<AstroMiddlewareInstance> | AstroMiddlewareInstance
astro@4.2.5
미들웨어를 로드하기 위한 인스턴스를 정의합니다.
actions
섹션 제목: “actions”타입: () => Promise<{ server: Record<string, ActionClient>; }> | { server: Record<string, ActionClient>; }
astro@5.4.2
액션 이름을 호출 가능한 함수에 매핑하는 server 속성을 가진 객체 또는 해당 객체를 반환하는 함수입니다.
checkOrigin
섹션 제목: “checkOrigin”타입: boolean
astro@4.6.0
보안 구성에서 오리진 검사가 활성화되어 있는지 여부를 결정합니다.
allowedDomains
섹션 제목: “allowedDomains”타입: Partial<RemotePattern>[]
요청 시 렌더링을 사용할 때 들어오는 요청에 대해 허용된 호스트 패턴의 구성된 목록을 지정합니다.
sessionConfig
섹션 제목: “sessionConfig”타입: SessionConfig<TDriver> & { driverModule?: () => Promise<{ default: () => unstorage.Driver }>; }
astro@5.1.0
해결된 세션 구성과 사용 중인 드라이버를 정의하는 추가 속성을 포함하는 객체입니다.
cacheDir
섹션 제목: “cacheDir”타입: string | URL
astro@5.2.0
빌드 아티팩트 캐싱을 위해 설정된 디렉터리를 지정합니다.
srcDir
섹션 제목: “srcDir”타입: string | URL
astro@5.2.0
Astro가 사이트를 읽어 들일 설정된 디렉터리를 지정합니다.
outDir
섹션 제목: “outDir”타입: string | URL
astro@5.2.0
최종 빌드 결과물을 저장할 설정된 디렉터리를 지정합니다.
publicDir
섹션 제목: “publicDir”타입: string | URL
astro@5.2.0
정적 자산을 위해 설정된 디렉터리를 지정합니다.
buildClientDir
섹션 제목: “buildClientDir”타입: string | URL
astro@5.2.0
빌드 경로 내에서 클라이언트 측 빌드 아티팩트(예: JavaScript, CSS)가 출력될 경로를 결정합니다.
buildServerDir
섹션 제목: “buildServerDir”타입: string | URL
astro@5.2.0
빌드 경로 내에서 서버 측 빌드 아티팩트가 출력될 경로를 결정합니다.
csp
섹션 제목: “csp”타입: SSRManifestCSP | undefined
astro@5.9.0
콘텐츠 보안 정책 구성을 설명하는 객체입니다.
internalFetchHeaders
섹션 제목: “internalFetchHeaders”타입: Record<string, string>
astro@5.15.0
렌더링 중 발생하는 내부 fetch 요청에 자동으로 추가되는 헤더를 지정합니다.
SSRManifestCSP
섹션 제목: “SSRManifestCSP”
추가된 버전:
astro@5.9.0
콘텐츠 보안 정책 구성을 설명합니다.
cspDestination
섹션 제목: “cspDestination”타입: 'adapter' | 'meta' | 'header' | undefined
CSP 지시어를 meta 요소로 삽입할지, 응답 header로 삽입할지, 응답 헤더 설정을 지원하는 어댑터를 통해 삽입할지 여부를 지정합니다.
algorithm
섹션 제목: “algorithm”타입: 'SHA-256' | 'SHA-384' | 'SHA-512'
설정된 해시 함수를 지정합니다.
scriptHashes
섹션 제목: “scriptHashes”타입: string[]
프로젝트 스크립트용으로 생성된 해시 목록과 외부 스크립트용으로 사용자가 제공한 해시 목록을 지정합니다.
scriptResources
섹션 제목: “scriptResources”타입: string[]
설정된 스크립트 리소스와 삽입된 스크립트 리소스를 결합한 유효한 소스 목록을 지정합니다.
isStrictDynamic
섹션 제목: “isStrictDynamic”타입: boolean
설정에서 동적 스크립트 삽입 지원이 활성화되었는지 여부를 결정합니다.
styleHashes
섹션 제목: “styleHashes”타입: string[]
프로젝트 스타일용으로 생성된 해시 목록과 외부 스타일용으로 사용자가 제공한 해시 목록을 지정합니다.
styleResources
섹션 제목: “styleResources”타입: string[]
설정된 스타일 리소스와 삽입된 스타일 리소스를 결합한 유효한 소스 목록을 지정합니다.
directives
섹션 제목: “directives”타입: CspDirective[]
특정 콘텐츠 유형에 대해 설정된 유효한 소스 목록을 지정합니다.
ValidRedirectStatus
섹션 제목: “ValidRedirectStatus”타입: 301 | 302 | 303 | 307 | 308 | 300 | 304
지원되는 리디렉션 상태 코드들의 유니언입니다.
사용 중단된 타입 가져오기
섹션 제목: “사용 중단된 타입 가져오기”다음 타입들은 더 이상 권장되지 않으며, 향후 주요 버전에서 제거될 예정입니다.
IntegrationRouteData
섹션 제목: “IntegrationRouteData”이 타입은 v5.0부터 사용 중단되었습니다. 대신 IntegrationResolvedRoute를 사용하세요.
통합에서 사용되는 RouteData의 축소된 버전입니다.
type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin'> & { redirectRoute?: IntegrationRouteData;};redirectRoute
섹션 제목: “redirectRoute”타입: IntegrationRouteData | undefined
RouteData.type의 값이 redirect인 경우, 값은 리디렉션할 경로의 IntegrationRouteData를 포함합니다. 그렇지 않으면 값은 undefined가 됩니다.
astro add를 통한 설치 허용
섹션 제목: “astro add를 통한 설치 허용”astro add 명령어는 사용자들이 프로젝트에 통합 기능과 어댑터를 쉽게 추가할 수 있도록 합니다. 만약 여러분의 통합 기능을 이 도구로 설치할 수 있도록 하려면, package.json의 keywords 필드에 astro-integration을 추가하세요:
{ "name": "example", "keywords": ["astro-integration"],}통합 기능을 npm에 게시하면, astro add example을 실행하여 package.json에 지정된 모든 피어 의존성과 함께 패키지를 설치합니다. 또한 다음과 같이 사용자 astro.config.*에 통합 기능이 적용됩니다.
import { defineConfig } from 'astro/config';import example from 'example';
export default defineConfig({ integrations: [example()],})통합 기능 정의가 1) default export이고 2) 함수라고 가정합니다. astro-integration 키워드를 추가하기 전에 이 두 가지가 사실인지 확인하세요!
통합 순서
섹션 제목: “통합 순서”모든 통합 기능은 구성된 순서대로 실행됩니다. 예를 들어, 사용자 astro.config.*의 배열 [react(), svelte()]의 경우, react가 svelte보다 먼저 실행됩니다.
통합 기능은 어떤 순서로든 실행되는 것이 이상적입니다. 이것이 불가능하다면, 사용자 integrations 구성 배열에서 통합 기능이 맨 처음 또는 맨 마지막에 와야 한다고 문서에 명시하는 것이 좋습니다.
통합을 프리셋으로 결합
섹션 제목: “통합을 프리셋으로 결합”통합 기능은 여러 개의 더 작은 통합 기능의 모음으로 작성될 수도 있습니다. 이러한 모음을 프리셋이라고 부릅니다. 단일 통합 객체를 반환하는 팩토리 함수를 생성하는 대신, 프리셋은 통합 객체의 배열을 반환합니다. 이는 여러 개의 통합 기능을 통해 복잡한 기능을 구축하는 데 유용합니다.
integrations: [ // 예시: examplePreset()이 다음을 반환하는 경우: [integrationOne, integrationTwo, ...etc] examplePreset()]커뮤니티 리소스
섹션 제목: “커뮤니티 리소스”- Build your own Astro Integrations - Emmanuel Ohans, FreeCodeCamp
- Astro Integration Template - Florian Lefebvre, GitHub