Astro's 1.14 release introduced the Content Layer API, extending content collections beyond local files. While Astro provides loaders for common data sources (RSS, CSV, etc.), creating custom loaders is straightforward. This guide demonstrates building a loader for a dad joke API.
Project Setup
Begin by creating a new Astro project:
<code class="language-bash">npm create astro@latest</code>
Follow the CLI prompts. Then start the development server:
<code class="language-bash">npm run dev</code>
Access your project at http://localhost:4321
.
Enabling the Experimental API
The Content Layer API is experimental. Enable it by modifying astro.config.mjs
:
<code class="language-javascript">// astro.config.mjs import { defineConfig } from 'astro/config'; export default defineConfig({ experimental: { contentLayer: true, }, });</code>
Creating the Loader
Create a new file (e.g., src/loaders/jokes.ts
) to house your loader. This example uses TypeScript, though it's not mandatory.
<code class="language-typescript">// src/loaders/jokes.ts import type { Loader } from 'astro/loaders'; export const jokesLoader: Loader = { name: 'jokes', load: async (context) => { const response = await fetch('https://icanhazdadjoke.com/', { headers: { Accept: 'application/json', }, }); const json = await response.json(); context.store.set({ id: json.id, data: json, }); }, };</code>
A loader comprises:
name
(required): The loader's identifier.load
(required): The asynchronous function fetching and processing data. It receives a context
object providing access to the data store and logger.schema
(optional): A Zod schema for data validation.Connecting the Loader to a Collection
Create a configuration file (e.g., src/content/config.ts
) to define your collection:
<code class="language-typescript">// src/content/config.ts import { defineCollection } from 'astro:content'; import { jokesLoader } from '../loaders/jokes'; const jokes = defineCollection({ loader: jokesLoader, }); export const collections = { jokes, };</code>
Accessing the Data
In an Astro component, access the data using getCollection
:
<code class="language-astro">--- import { getCollection } from 'astro:content'; const jokes = await getCollection('jokes'); --- <ul> {jokes.map(joke => <li>{joke.data.joke}</li>)} </ul></code>
Building and Running
Run npm run build
. The loader will execute, fetching and storing the joke data. The Astro component will then display the fetched joke.
Conclusion
This illustrates building a basic Astro collection loader. This approach can be extended to handle more complex data sources and incorporate features like error handling and pagination. The modular design allows for creating reusable loaders, potentially packaging them for wider use.
The above is the detailed content of How to build an Astro collection loader. For more information, please follow other related articles on the PHP Chinese website!