diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 365a3a2d8fa6b..983c1146f96e1 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,10 +1,8 @@ #### Description (required) - - - + #### Related issues & labels (optional) diff --git a/.github/hacktoberfest.md b/.github/hacktoberfest.md index d006f611d8e6d..297503193fa5a 100644 --- a/.github/hacktoberfest.md +++ b/.github/hacktoberfest.md @@ -52,4 +52,4 @@ Reviewed a translation PR? We want you to get credit, too! **Create a PR followi If you have any questions, just ask, and thank you for helping to translate the Astro Docs! -During Hacktoberfest 2023, we've received 2 translation PR reviews from helpful contributors. Thank you! +During Hacktoberfest 2023, we've received 4 translation PR reviews from helpful contributors. Thank you! diff --git a/contributor-guides/translating-astro-docs.md b/contributor-guides/translating-astro-docs.md index fac7f2492deb5..73cc93adde86b 100644 --- a/contributor-guides/translating-astro-docs.md +++ b/contributor-guides/translating-astro-docs.md @@ -30,7 +30,7 @@ Unfortunately, we cannot support all languages at this time, and must prioritize We receive several translation PRs to our repository daily, meaning one of the most helpful and impactful ways to contribute is through **reviews** so that all of these wonderful translations can be properly checked before being published. Keep reading to find out how to contribute on GitHub! -If you're a beginner when it comes to reviewing GitHub PRs and translations, we got you covered in our [Reviewer Process section](#reviewer). +If you're a beginner when it comes to reviewing GitHub PRs and translations, we got you covered in our [Reviewer Process section](#review-process). > **Note** > Did you know that reviews and translations count towards your Astro Badge? [Astro Badges](https://astro.badg.es/) is a community initiative made to award contributions to Astro through achievements you can showcase in your GitHub profile! diff --git a/contributor-guides/writing-and-style-guide.md b/contributor-guides/writing-and-style-guide.md index 22fe22fdb75bb..c7fb9ad674f59 100644 --- a/contributor-guides/writing-and-style-guide.md +++ b/contributor-guides/writing-and-style-guide.md @@ -374,7 +374,7 @@ Here are two examples of what our code snippets look like written in Markdown, j #### Example 2 - use the file name as a title (alt method) -- apply "+ diff" styling (green backround) to any occurrence of ` +``` + +Stattdessen verwende ein clientseitiges Skript, um den event handler hinzuzufügen, so wie du es in reinem JavaScript tun würdest: + +```astro +--- +// tu-stattdessen-das.astro +--- + + +``` +::: + +### Dynamisches HTML + +Lokale Variablen können in JSX-ähnlichen Funktionen verwendet werden, um dynamisch generierte HTML-Elemente zu erzeugen: + +```astro title="src/components/DynamicHtml.astro" "{item}" +--- +const tiere = ["Dog", "Cat", "Platypus"]; +--- + +``` + +Astro kann bedingt HTML anzeigen, indem es JSX-logische Operatoren und Ternär-Ausdrücke verwendet. + +```astro title="src/components/ConditionalHtml.astro" "visible" +--- +const sichtbar = true; +--- +{sichtbar &&

Zeige mich!

} + +{sichtbar ?

Zeige mich!

:

Zeige mich sonst!

} +``` + +### Dynamische Tags + +Du kannst auch dynamische Tags verwenden, indem du eine Variable auf einen HTML-Tag-Namen oder einen Komponentenimport setzt: + +```astro title="src/components/DynamicTags.astro" /Element|(?Hallo! + +``` + +Bei der Verwendung von dynamischen Tags: + +- **Die Variablennamen müssen großgeschrieben sein.** Verwende beispielsweise `Element` und nicht `element`. Andernfalls wird Astro versuchen, deinen Variablennamen als wörtlichen HTML-Tag zu rendern. + +- **Hydratisierungsanweisungen werden nicht unterstützt.** Bei Verwendung von Hydratisierungsanweisungen [`client:*`](/de/core-concepts/framework-components/#interaktive-komponenten-hydratisieren) muss Astro wissen, welche Komponenten für die Produktion gebündelt werden sollen, und das Muster dynamischer Tags verhindert dies. + +### Fragmente + +Astro unterstützt die Verwendung von ` ` oder der Kurzform `<> `. + +Fragments können nützlich sein, um Wrapper-Elemente zu vermeiden, wenn [`set:*`-Anweisungen](/de/reference/directives-reference/#sethtml) hinzugefügt werden, wie im folgenden Beispiel: + +```astro title="src/components/SetHtml.astro" "Fragment" +--- +const htmlString = '

Roher HTML-Inhalt

'; +--- + +``` + +### Unterschiede zwischen Astro und JSX + +Die Syntax der Astro-Komponenten ist eine Erweiterung von HTML. Sie wurde so entworfen, dass sie für jeden mit HTML- oder JSX-Erfahrung vertraut wirkt, aber es gibt ein paar wesentliche Unterschiede zwischen `.astro`-Dateien und JSX. + +#### Attribute + +In Astro verwendest du den Standard `kebab-case` für alle HTML-Attribute anstelle von `camelCase`, wie es in JSX verwendet wird. Dies gilt sogar für `class`, was von React nicht unterstützt wird. + +```jsx del={1} ins={2} title="example.astro" +
+
+``` + +#### Mehrere Elemente + +Eine Astro-Komponentenvorlage kann mehrere Elemente rendern, ohne dass alles in ein einzelnes `
` oder `<>` eingebettet werden muss, im Gegensatz zu JavaScript oder JSX. + +```astro title="src/components/RootElements.astro" +--- +// Vorlage mit mehreren Elementen +--- +

Es ist nicht erforderlich, Elemente in einen einziges umschließendes Element einzubetten.

+

Astro unterstützt mehrere Root-Elemente in einer Vorlage.

+``` + +#### Kommentare + +In Astro kannst du Standard-HTML-Kommentare oder Kommentare im JavaScript-Stil verwenden. + +```astro title="example.astro" +--- +--- + +{/* Die Syntax für JS-Kommentare ist ebenfalls gültig */} +``` + +:::caution +HTML-Kommentare werden in dem DOM des Browsers enthalten sein, während JavaScript-Kommentare übersprungen werden. Um TODO-Nachrichten oder andere nur für die Entwicklung bestimmte Erläuterungen zu hinterlassen, empfiehlt es sich, Kommentare im JavaScript-Stil zu verwenden. +::: diff --git a/src/content/docs/de/core-concepts/endpoints.mdx b/src/content/docs/de/core-concepts/endpoints.mdx index 608d54790e5ed..01dcf4feffc35 100644 --- a/src/content/docs/de/core-concepts/endpoints.mdx +++ b/src/content/docs/de/core-concepts/endpoints.mdx @@ -99,7 +99,7 @@ Im Gegensatz zum `static`-Modus werden die Endpunkte bei der Konfiguration des ` :::note -Stelle sicher, dass du [SSR aktivierst](/de/guides/server-side-rendering/#ssr-in-deinem-projekt-aktivieren), bevor du diese Beispiele ausprobierst. +Stelle sicher, dass du [SSR aktivierst](/de/guides/server-side-rendering/), bevor du diese Beispiele ausprobierst. ::: Server-Endpunkte können auf `params` zugreifen, ohne `getStaticPaths` zu exportieren, und sie können ein [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)-Objekt zurückgeben, welches dir ermöglicht, Statuscodes und Header zu setzen: diff --git a/src/content/docs/de/guides/deploy.mdx b/src/content/docs/de/guides/deploy.mdx index e21dcc2c4663a..fe3866cbacc5b 100644 --- a/src/content/docs/de/guides/deploy.mdx +++ b/src/content/docs/de/guides/deploy.mdx @@ -77,6 +77,6 @@ Die Build-Ausgabe wird standardmäßig ins Verzeichnis `dist/` geschrieben. Dies :::note Bevor du deine Website mit aktiviertem [SSR (serverseitigem Rendern)](/de/guides/server-side-rendering/) veröffentlichst, stelle bitte Folgendes sicher: - - Du hast den [geeigneten SSR-Adapter](/de/guides/server-side-rendering/#ssr-in-deinem-projekt-aktivieren) als Projektabhängigkeit installiert. + - Du hast den [geeigneten SSR-Adapter](/de/guides/server-side-rendering/) als Projektabhängigkeit installiert. - Du hast die [Konfiguration angepasst](/de/reference/configuration-reference/#integrations) und den Adapter zu den Imports sowie dem Standard-Export deiner `astro.config.mjs`-Datei hinzugefügt. ::: diff --git a/src/content/docs/de/guides/rss.mdx b/src/content/docs/de/guides/rss.mdx index 0b66575d6ccbd..6d61b2e5e4b0c 100644 --- a/src/content/docs/de/guides/rss.mdx +++ b/src/content/docs/de/guides/rss.mdx @@ -11,7 +11,7 @@ Astro unterstützt die schnelle, automatische Generierung von RSS-Feeds für Blo ## Einrichten von `@astrojs/rss` -Das `@astrojs/rss`-Paket bietet Hilfsfunktionen zur Erzeugung von RSS-Feeds mithilfe von [API-Endpunkten](/de/core-concepts/astro-pages/#nicht-html-seiten). Dies ermöglicht statische Feeds _und_ die On-Demand-Generierung bei Verwendung eines [SSR-Adapters](/de/guides/server-side-rendering/#ssr-in-deinem-projekt-aktivieren). +Das `@astrojs/rss`-Paket bietet Hilfsfunktionen zur Erzeugung von RSS-Feeds mithilfe von [API-Endpunkten](/de/core-concepts/astro-pages/#nicht-html-seiten). Dies ermöglicht statische Feeds _und_ die On-Demand-Generierung bei Verwendung eines [SSR-Adapters](/de/guides/server-side-rendering/). 1. Installiere `@astrojs/rss` mit deinem bevorzugten Paketmanager: diff --git a/src/content/docs/de/recipes.mdx b/src/content/docs/de/recipes.mdx new file mode 100644 index 0000000000000..e315f664d12f1 --- /dev/null +++ b/src/content/docs/de/recipes.mdx @@ -0,0 +1,38 @@ +--- +title: Mehr Anleitungen +description: Schau dir geführte Beispiele für die Erstellung von Features in Astro an. +--- + +import RecipesNav from '~/components/RecipesNav.astro'; + +Schau dir geführte Beispiele für das Hinzufügen von Features zu deinem Astro-Projekt an. + +## Offizielle Anleitungen + + + +## Ressourcen aus der Community + +Füge hier deine eigene Anleitung hinzu! Weitere Informationen findest du in unserem [recipes contributing guide](https://github.com/withastro/docs/blob/main/contributor-guides/submitting-a-recipe.md). + +- [Use a dynamic filename when importing images](https://vaihe.com/blog/astro/astro-dynamic-image-prop/) +- [Add animated page transitions with Swup](https://navillus.dev/blog/astro-plus-swup) +- [Use UnoCSS in Astro](https://www.elian.codes/blog/23-02-11-implementing-unocss-in-astro/) +- [Build a table of contents from Astro's Markdown headings](https://kld.dev/building-table-of-contents/) +- [Create a Remark plugin to remove runts from your Markdown files](https://eatmon.co/blog/remove-runts-markdown/) +- [Add searching to your site with Pagefind](https://blog.otterlord.dev/posts/astro-search/) +- [Add searching to your site with Fuse.js](https://www.youtube.com/watch?v=XnV_2MWqAhQ) +- [Get VSCode, ESLint & Prettier working with Astro](https://patheticgeek.dev/blog/astro-prettier-eslint-vscode) +- [Enhance your Astro builds: modify HTML files post-build](https://straffesites.com/en/blog/optimize-astro-html-post-build) +- [Add dark mode to Astro with Tailwind CSS](https://www.kevinzunigacuellar.com/blog/dark-mode-in-astro/) +- [Generate localized sitemaps for your Astro and Storyblok project](https://straffesites.com/en/blog/localized-sitemap-astro-storyblok) +- [Integrate Prettier with Astro and Tailwind CSS](https://straffesites.com/en/blog/integrate-prettier-astro-tailwindcss) +- [Add an RSS feed to Astro using Storyblok's stories](https://straffesites.com/en/blog/rss-feed-astro-storyblok) +- [Using tRPC in Astro](https://www.thomasledoux.be/blog/using-trpc-astro-islands-react) +- [How to make your Astro website multilingual with Crowdin: Astro localization guide](https://crowdin.com/blog/2023/06/21/astro-localization-and-i18n) +- [Add blog post images to your Astro RSS Feed](https://webreaper.dev/posts/astro-rss-feed-blog-post-images/) +- [Setting up micro-frontends with Astro](https://medium.com/@sergio.a.soria/setting-up-micro-frontends-with-astro-and-ecma-script-modules-137340d2c520) +- [Add username and password authentication with Lucia](https://lucia-auth.com/guidebook/sign-in-with-username-and-password/astro) +- [Add Github OAuth with Lucia](https://lucia-auth.com/guidebook/github-oauth/astro) +- [Integrating Sentry with Astro](https://akashrajpurohit.com/blog/seamless-error-tracking-integrating-sentry-with-astro/) +- [Set Up Draft Pages Effectively in Astro with Config-Driven Content Authoring](https://akashrajpurohit.com/blog/set-up-draft-pages-effectively-in-astro-with-configdriven-content-authoring/) diff --git a/src/content/docs/en/core-concepts/astro-components.mdx b/src/content/docs/en/core-concepts/astro-components.mdx index 20c0c397cdbbc..1ddb32037d649 100644 --- a/src/content/docs/en/core-concepts/astro-components.mdx +++ b/src/content/docs/en/core-concepts/astro-components.mdx @@ -258,6 +258,11 @@ Named slots can also be passed to [UI framework components](/en/core-concepts/fr ::: +:::note +An astro slot name can not be dynamically generated, such as within a map function. If this feature is needed within UI framework components, it might be best to generate these dynamic slots within the framework itself. +::: + + ### Fallback Content for Slots Slots can also render **fallback content**. When there are no matching children passed to a slot, a `` element will render its own placeholder children. diff --git a/src/content/docs/en/core-concepts/astro-pages.mdx b/src/content/docs/en/core-concepts/astro-pages.mdx index c230774b59f27..c29c8acbee644 100644 --- a/src/content/docs/en/core-concepts/astro-pages.mdx +++ b/src/content/docs/en/core-concepts/astro-pages.mdx @@ -4,6 +4,8 @@ description: An introduction to Astro pages i18nReady: true --- +import Since from '~/components/Since.astro' + **Pages** are files that live in the `src/pages/` subdirectory of your Astro project. They are responsible for handling routing, data loading, and overall page layout for every page in your website. ## Supported page files @@ -51,6 +53,8 @@ Astro pages use the `.astro` file extension and support the same features as [As ``` +A page must produce a full HTML document. If not explicitly included, Astro will add the necessary `` declaration and `` content to any `.astro` component located within `src/pages/` by default. You can opt-out of this behavior on a per-component basis by marking it as a [partial](#page-partials) page. + To avoid repeating the same HTML elements on every page, you can move common `` and `` elements into your own [layout components](/en/core-concepts/layouts/). You can use as many or as few layout components as you'd like. ```astro {3} // @@ -96,3 +100,76 @@ For a custom 404 error page, you can create a `404.astro` or `404.md` file in `/ This will build to a `404.html` page. Most [deploy services](/en/guides/deploy/) will find and use it. +## Page Partials + + + +:::caution +Page partials are intended to be used in conjunction with a front-end library, such as [htmx](https://htmx.org/) or [Unpoly](https://unpoly.com/). You can also use them if you are comfortable writing low-level front-end JavaScript. For this reason they are an advanced feature. + +Additionally, partials should not be used if the component contains scoped styles or scripts, as these elements will be stripped from the HTML output. If you need scoped styles, it is better to use regular, non-partial pages along with a frontend library that knows how to merge the contents into the head. +::: + +Partials are page components located within `src/pages/` that are not intended to render as full pages. + +Like components located outside of this folder, these files do not automatically include the `` declaration, nor any `` content such as scoped styles and scripts. + +However, because they are located in the special `src/pages/` directory, the generated HTML is available at a URL corresponding to its file path. This allows a rendering library (e.g. htmx, Stimulus, jQuery) to access it on the client and load sections of HTML dynamically on a page without a browser refresh or page navigation. + +Partials, when combined with a rendering library, provide an alternative to [Astro islands](/en/concepts/islands/) and [` + + +
+
Target here
+ + +
+``` + +The `.astro` partial must exist at the corresponding file path, and include an export defining the page as a partial: + +```astro title="src/pages/partials/clicked.astro" {2} +--- +export const partial = true; +--- +
I was clicked!
+``` + +See the [htmx documentation](https://htmx.org/docs/) for more details on using htmx. diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index acd172d242bcb..2e885a85535a2 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -99,7 +99,7 @@ But, unlike in `static` mode, when you configure `server` mode, the endpoints wi :::note -Be sure to [enable SSR](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) before trying these examples. +Be sure to [enable SSR](/en/guides/server-side-rendering/) before trying these examples. ::: Server endpoints can access `params` without exporting `getStaticPaths`, and they can return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object, allowing you to set status codes and headers: diff --git a/src/content/docs/en/core-concepts/rendering-modes.mdx b/src/content/docs/en/core-concepts/rendering-modes.mdx new file mode 100644 index 0000000000000..83d353a48f283 --- /dev/null +++ b/src/content/docs/en/core-concepts/rendering-modes.mdx @@ -0,0 +1,54 @@ +--- +title: "Rendering Modes" +i18nReady: true +--- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; +import RecipeLinks from '~/components/RecipeLinks.astro'; + +Your Astro project code must be **rendered** to HTML in order to be displayed on the web. + +Astro pages, routes, and API endpoints can be either [pre-rendered at build time](#pre-rendered) or [rendered on demand by a server](#on-demand-rendered) when a route is requested. With [Astro islands](/en/concepts/islands/), you can also include some client-side rendering when necessary. + +In Astro, most of the processing occurs on the server, instead of in the browser. This generally makes your site or app faster than client-side rendering when viewed on less-powerful devices or on slower internet connections. Server-rendered HTML is fast, SEO friendly, and accessible by default. + +## Server `output` modes + +You can configure how your pages are rendered in your [`output` configuration](/en/reference/configuration-reference/#output). + +### Pre-rendered + +The **default rendering mode is __`output: 'static'`__**, which creates the HTML for all your page routes at build time. + +In this mode, **your entire site will be pre-rendered** and the server will have all pages built ahead of time and ready to send to the browser. The same HTML document is sent to the browser for every visitor, and a full-site rebuild is required to update the contents of the page. This method is also known as **static site generation (SSG)**. + +By default, all Astro projects are configured to be pre-rendered at build time (statically-generated) to provide the most lightweight browser experience. The browser does not need to wait for any HTML to build because the server does not need to generate any pages on demand. Your site is not dependent on the performance of a backend data source, and once built, will remain available to visitors as a static site as long as your server is functioning. + +Static sites can include [Astro islands](/en/concepts/islands/) for interactive UI components (or even entire embedded client-side rendered apps!) written in the [UI framework of your choice](/en/core-concepts/framework-components/) in an otherwise static, pre-rendered page. + +Astro's [View Transitions API](/en/guides/view-transitions/) are also available in `static` mode for animation and state persistence across page navigation. Static sites can also use [middleware](/en/guides/middleware/) to intercept and transform response data from a request. + +:::tip +Astro's default `static` mode is a powerful, modern-feeling choice for content-heavy sites that update infrequently, and display the same page content to all visitors. +::: + +### On-demand rendered + +Astro's other two output modes can be configured to enable **on-demand rendering of some or all of your pages, routes or API endpoints**: + - __`output: 'server'`__ for highly dynamic sites with most or all on-demand routes. + - __`output: 'hybrid'`__ for mostly static sites with some on-demand routes. + +Since they are generated per visit, these routes can be customized for each viewer. For example, a page rendered on demand can show a logged-in user their account information or display freshly updated data without requiring a full-site rebuild. On-demand rendering on the server at request time is also known as **server-side rendering (SSR)**. + +[Consider enabling `server` or `hybrid` mode](/en/guides/server-side-rendering/#enable-on-demand-server-rendering) in your Astro project if you need the following: + +- **API endpoints**: Create specific pages that function as API endpoints for tasks like database access, authentication, and authorization while keeping sensitive data hidden from the client. + +- **Protected pages**: Restrict access to a page based on user privileges, by handling user access on the server. + +- **Frequently changing content**: Generate individual pages without requiring a static rebuild of your site. This is useful when the content of a page updates frequently, for example displaying data from an API called dynamically with `fetch()`. + +Both `server` and `hybrid` output modes allow you to include [Astro islands](/en/concepts/islands/) for interactivity (or even entire embedded client-side rendered apps!) in your choice of [UI frameworks](/en/core-concepts/framework-components/). With [middleware](/en/guides/middleware/) and Astro's [View Transitions API](/en/guides/view-transitions/) for animations and preserving state across route navigations, even highly interactive apps are possible. + +:::tip +On demand server-rendering in Astro provides a true app experience without the JavaScript overhead of a client-side, single-page application. +::: diff --git a/src/content/docs/en/editor-setup.mdx b/src/content/docs/en/editor-setup.mdx index 6f84e67f00b54..2f8735999d32d 100644 --- a/src/content/docs/en/editor-setup.mdx +++ b/src/content/docs/en/editor-setup.mdx @@ -36,6 +36,7 @@ Our amazing community maintains several extensions for other popular editors, in - [Nova Extension](https://extensions.panic.com/extensions/sciencefidelity/sciencefidelity.astro/) Community - Provides syntax highlighting and code completion for Astro inside of Nova - [Vim Plugin](https://github.com/wuelnerdotexe/vim-astro) Community - Provides syntax highlighting, indentation, and code folding support for Astro inside of Vim or Neovim - Neovim [LSP](https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#astro) and [TreeSitter](https://github.com/virchau13/tree-sitter-astro) Plugins Community - Provides syntax highlighting, treesitter parsing, and code completion for Astro inside of Neovim +- Emacs - See instructions for [Configuring Emacs and Eglot](https://medium.com/@jrmjrm/configuring-emacs-and-eglot-to-work-with-astro-language-server-9408eb709ab0) Community to work with Astro ## In-Browser Editors @@ -75,7 +76,7 @@ To get started, first install Prettier and the plugin: ```shell - pnpm install -D prettier prettier-plugin-astro + pnpm add -D prettier prettier-plugin-astro ``` diff --git a/src/content/docs/en/guides/backend/google-firebase.mdx b/src/content/docs/en/guides/backend/google-firebase.mdx index 33c9d6b505c1f..7062002fc9d0a 100644 --- a/src/content/docs/en/guides/backend/google-firebase.mdx +++ b/src/content/docs/en/guides/backend/google-firebase.mdx @@ -19,7 +19,7 @@ See our separate guide for [deploying to Firebase hosting](/en/guides/deploy/goo ### Prerequisites - A [Firebase project with a web app configured](https://firebase.google.com/docs/web/setup). -- An Astro project with [server-side rendering (SSR)](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) enabled. +- An Astro project with [server-side rendering (SSR)](/en/guides/server-side-rendering/) enabled. - Firebase credentials: You will need two sets of credentials to connect Astro to Firebase: - Web app credentials: These credentials will be used by the client side of your app. You can find them in the Firebase console under *Project settings > General*. Scroll down to the **Your apps** section and click on the **Web app** icon. - Project credentials: These credentials will be used by the server side of your app. You can generate them in the Firebase console under *Project settings > Service accounts > Firebase Admin SDK > Generate new private key*. @@ -92,7 +92,7 @@ To connect Astro with Firebase, install the following packages using the single ```shell - pnpm install firebase firebase-admin + pnpm add firebase firebase-admin ``` diff --git a/src/content/docs/en/guides/backend/supabase.mdx b/src/content/docs/en/guides/backend/supabase.mdx index 7468a755ced1a..3847b9d455324 100644 --- a/src/content/docs/en/guides/backend/supabase.mdx +++ b/src/content/docs/en/guides/backend/supabase.mdx @@ -3,11 +3,487 @@ title: Supabase & Astro description: Add a backend to your project with Supabase type: backend service: Supabase -stub: true --- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' +import FileTree from '~/components/FileTree.astro' [Supabase](https://supabase.com/) is an open source Firebase alternative. It provides a Postgres database, authentication, edge functions, realtime subscriptions, and storage. +## Initializing Supabase in Astro + +### Prerequisites + +- A Supabase project. If you don't have one, you can sign up for free at [supabase.com](https://supabase.com/) and create a new project. +- An Astro project with [server-side rendering (SSR)](/en/guides/server-side-rendering/) enabled. +- Supabase credentials for your project. You can find these in the **Settings > API** tab of your Supabase project. + - `SUPABASE_URL`: The URL of your Supabase project. + - `SUPABASE_ANON_KEY`: The anonymous key for your Supabase project. + +### Adding Supabase credentials + +To add your Supabase credentials to your Astro project, add the following to your `.env` file: + +```ini title=".env" +SUPABASE_URL=YOUR_SUPABASE_URL +SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY +``` + +Now, these environment variables are available in your project. + +If you would like to have IntelliSense for your environment variables, edit or create the `env.d.ts` in your `src/` directory and add the following: + +```ts title="src/env.d.ts" +interface ImportMetaEnv { + readonly SUPABASE_URL: string + readonly SUPABASE_ANON_KEY: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} +``` + +:::tip +Read more about [environment variables](/en/guides/environment-variables/) and `.env` files in Astro. +::: + +Your project should now include these files: + + +- src/ + - **env.d.ts** +- **.env** +- astro.config.mjs +- package.json + + +### Installing dependencies + +To connect to Supabase, you will need to install `@supabase/supabase-js` in your project. + + + + ```shell + npm install @supabase/supabase-js + ``` + + + ```shell + pnpm add @supabase/supabase-js + ``` + + + ```shell + yarn add @supabase/supabase-js + ``` + + + +Next, create a folder named `lib` in your `src/` directory. This is where you will add your Supabase client. + +In `supabase.ts`, add the following to initialize your Supabase client: + +```ts title="src/lib/supabase.ts" +import { createClient } from "@supabase/supabase-js"; + +export const supabase = createClient( + import.meta.env.SUPABASE_URL, + import.meta.env.SUPABASE_ANON_KEY, +); +``` + +Now, your project should include these files: + + +- src/ + - lib/ + - **supabase.ts** + - env.d.ts +- .env +- astro.config.mjs +- package.json + + +## Adding authentication with Supabase + +Supabase provides authentication out of the box. It supports email/password authentication and OAuth authentication with many providers including GitHub, Google, and several others. + +### Prerequisites + +- An Astro project [initialized with Supabase](#initializing-supabase-in-astro). +- A Supabase project with email/password authentication enabled. You can enable this in the **Authentication > Providers** tab of your Supabase project. + +### Creating auth server endpoints + +To add authentication to your project, you will need to create a few server endpoints. These endpoints will be used to register, sign in, and sign out users. + +- `POST /api/auth/register`: to register a new user. +- `POST /api/auth/signin`: to sign in a user. +- `GET /api/auth/signout`: to sign out a user. + +Create these endpoints in the `src/pages/api/auth` directory of your project. Your project should now include these new files: + + +- src/ + - lib/ + - supabase.ts + - pages/ + - api/ + - auth/ + - **signin.ts** + - **signout.ts** + - **register.ts** + - env.d.ts +- .env +- astro.config.mjs +- package.json + + +`register.ts` creates a new user in Supabase. It accepts a `POST` request with the an email and password. It then uses the Supabase SDK to create a new user. + +```ts title="src/pages/api/auth/register.ts" +import type { APIRoute } from "astro"; +import { supabase } from "../../../lib/supabase"; + +export const POST: APIRoute = async ({ request, redirect }) => { + const formData = await request.formData(); + const email = formData.get("email")?.toString(); + const password = formData.get("password")?.toString(); + + if (!email || !password) { + return new Response("Email and password are required", { status: 400 }); + } + + const { error } = await supabase.auth.signUp({ + email, + password, + }); + + if (error) { + return new Response(error.message, { status: 500 }); + } + + return redirect("/signin"); +}; +``` + +`signin.ts` signs in a user. It accepts a `POST` request with the an email and password. It then uses the Supabase SDK to sign in the user. + +```ts title="src/pages/api/auth/signin.ts" +import type { APIRoute } from "astro"; +import { supabase } from "../../../lib/supabase"; + +export const POST: APIRoute = async ({ request, cookies, redirect }) => { + const formData = await request.formData(); + const email = formData.get("email")?.toString(); + const password = formData.get("password")?.toString(); + + if (!email || !password) { + return new Response("Email and password are required", { status: 400 }); + } + + const { data, error } = await supabase.auth.signInWithPassword({ + email, + password, + }); + + if (error) { + return new Response(error.message, { status: 500 }); + } + + const { access_token, refresh_token } = data.session; + cookies.set("sb-access-token", access_token, { + path: "/", + }); + cookies.set("sb-refresh-token", refresh_token, { + path: "/", + }); + return redirect("/dashboard"); +}; +``` + +`signout.ts` signs out a user. It accepts a `GET` request and removes the user's access and refresh tokens. + +```ts title="src/pages/api/auth/signout.ts" +import type { APIRoute } from "astro"; + +export const GET: APIRoute = async ({ cookies, redirect }) => { + cookies.delete("sb-access-token", { path: "/" }); + cookies.delete("sb-refresh-token", { path: "/" }); + return redirect("/signin"); +}; +``` + +### Creating auth pages + +Now that you have created your server endpoints, create the pages that will use them. + +- `src/pages/register`: contains a form to register a new user. +- `src/pages/signin`: contains a form to sign in a user. +- `src/pages/dashboard`: contains a page that is only accessible to authenticated users. + +Create these pages in the `src/pages` directory. Your project should now include these new files: + + +- src/ + - lib/ + - supabase.ts + - pages/ + - api/ + - auth/ + - signin.ts + - signout.ts + - register.ts + - **register.astro** + - **signin.astro** + - **dashboard.astro** + - env.d.ts +- .env +- astro.config.mjs +- package.json + + +`register.astro` contains a form to register a new user. It accepts an email and password and sends a `POST` request to `/api/auth/register`. + +```astro title="src/pages/register.astro" +--- +import Layout from "../layouts/Layout.astro"; +--- + + +

Register

+

Already have an account? Sign in

+
+ + + + + +
+
+``` + +`signin.astro` contains a form to sign in a user. It accepts an email and password and sends a `POST` request to `/api/auth/signin`. It also checks for the presence of the access and refresh tokens. If they are present, it redirects to the dashboard. + +```astro title="src/pages/signin.astro" +--- +import Layout from "../layouts/Layout.astro"; + +const accessToken = cookies.get("sb-access-token"); +const refreshToken = cookies.get("sb-refresh-token"); + +if (accessToken && refreshToken) { + return redirect("/dashboard"); +} +--- + + +

Sign in

+

New here? Create an account

+
+ + + + + +
+
+``` + +`dashboard.astro` contains a page that is only accessible to authenticated users. It checks for the presence of the access and refresh tokens. If they are not present, it redirects to the sign in page. + +```astro title="src/pages/dashboard.astro" +--- +const accessToken = cookies.get("sb-access-token"); +const refreshToken = cookies.get("sb-refresh-token"); + +if (!accessToken || !refreshToken) { + return redirect("/signin"); +} + +const { data, error } = await supabase.auth.setSession({ + refresh_token: refreshToken.value, + access_token: accessToken.value, +}); + +if (error) { + cookies.delete("sb-access-token", { + path: "/", + }); + cookies.delete("sb-refresh-token", { + path: "/", + }); + + return redirect("/signin"); +} + +const email = data?.user?.email; +--- + +

Welcome {email}

+

We are happy to see you here

+
+ +
+
+``` + +### Adding OAuth authentication + +To add OAuth authentication to your project, you will need to edit your Supabase client to enable authentication flow with `"pkce"`. You can read more about authentication flows in the [Supabase documentation](https://supabase.com/docs/guides/auth/server-side-rendering#understanding-the-authentication-flow). + +```ts title="src/lib/supabase.ts" ins={6-10} +import { createClient } from "@supabase/supabase-js"; + +export const supabase = createClient( + import.meta.env.SUPABASE_URL, + import.meta.env.SUPABASE_ANON_KEY, + { + auth: { + flowType: "pkce", + }, + }, +); +``` + +Next, in the Supabase dashboard, enable the OAuth provider you would like to use. You can find the list of supported providers in the **Authentication > Providers** tab of your Supabase project. + +The following example uses GitHub as the OAuth provider. To connect your project to GitHub, follow the steps in the [Supabase documentation](https://supabase.com/docs/guides/auth/social-login/auth-github). + +Then, create a new server endpoint to handle the OAuth callback at `src/pages/api/auth/callback.ts`. This endpoint will be used to exchange the OAuth code for an access and refresh token. + +```ts title="src/pages/api/auth/callback.ts" +import type { APIRoute } from "astro"; +import { supabase } from "../../../lib/supabase"; + +export const GET: APIRoute = async ({ url, cookies, redirect }) => { + const authCode = url.searchParams.get("code"); + + if (!authCode) { + return new Response("No code provided", { status: 400 }); + } + + const { data, error } = await supabase.auth.exchangeCodeForSession(authCode); + + if (error) { + return new Response(error.message, { status: 500 }); + } + + const { access_token, refresh_token } = data.session; + + cookies.set("sb-access-token", access_token, { + path: "/", + }); + cookies.set("sb-refresh-token", refresh_token, { + path: "/", + }); + + return redirect("/dashboard"); +}; +``` + +Next, edit the sign in page to include a new button to sign in with the OAuth provider. This button should send a `POST` request to `/api/auth/signin` with the `provider` set to the name of the OAuth provider. + +```astro title="src/pages/signin.astro" ins={21} +--- +import Layout from "../layouts/Layout.astro"; + +const accessToken = cookies.get("sb-access-token"); +const refreshToken = cookies.get("sb-refresh-token"); + +if (accessToken && refreshToken) { + return redirect("/dashboard"); +} +--- + + +

Sign in

+

New here? Create an account

+
+ + + + + + +
+
+``` + +Finally, edit the sign in server endpoint to handle the OAuth provider. If the `provider` is present, it will redirect to the OAuth provider. Otherwise, it will sign in the user with the email and password. + +```ts title="src/pages/api/auth/signin.ts" ins={10-23} +import type { APIRoute } from "astro"; +import { supabase } from "../../../lib/supabase"; + +export const POST: APIRoute = async ({ request, cookies, redirect }) => { + const formData = await request.formData(); + const email = formData.get("email")?.toString(); + const password = formData.get("password")?.toString(); + const provider = formData.get("provider")?.toString(); + + if (provider) { + const { data, error } = await supabase.auth.signInWithOAuth({ + provider, + options: { + redirectTo: "http://localhost:4321/api/auth/callback" + }, + }); + + if (error) { + return new Response(error.message, { status: 500 }); + } + + return redirect(data.url); + } + + if (!email || !password) { + return new Response("Email and password are required", { status: 400 }); + } + + const { data, error } = await supabase.auth.signInWithPassword({ + email, + password, + }); + + if (error) { + return new Response(error.message, { status: 500 }); + } + + const { access_token, refresh_token } = data.session; + cookies.set("sb-access-token", access_token, { + path: "/", + }); + cookies.set("sb-refresh-token", refresh_token, { + path: "/", + }); + return redirect("/dashboard"); +}; +``` + +After creating the OAuth callback endpoint and editing the sign in page and server endpoint, your project should have the following file structure: + + +- src/ + - lib/ + - supabase.ts + - pages/ + - api/ + - auth/ + - signin.ts + - signout.ts + - register.ts + - callback.ts + - register.astro + - signin.astro + - dashboard.astro + - env.d.ts +- .env +- astro.config.mjs +- package.json + + ## Community Resources + - [Getting into the holiday spirit with Astro, React, and Supabase](https://www.aleksandra.codes/astro-supabase) - [Astro and Supabase auth demo](https://github.com/kevinzunigacuellar/astro-supabase) diff --git a/src/content/docs/en/guides/backend/xata.mdx b/src/content/docs/en/guides/backend/xata.mdx index fdd5281fd8015..a9ec7b6805048 100644 --- a/src/content/docs/en/guides/backend/xata.mdx +++ b/src/content/docs/en/guides/backend/xata.mdx @@ -97,9 +97,9 @@ const { records } = await xata.db.Posts.getPaginated({ ---
    - {records.map(post) => ( + {records.map((post) => (
  • {post.title}
  • - )} + ))}
``` It's important to note the SDK needs to be regenerated everytime your schema changes. So, avoid making changes to the generated files the Xata CLI creates because once schema updates, your changes will be overwritten. diff --git a/src/content/docs/en/guides/cms/buttercms.mdx b/src/content/docs/en/guides/cms/buttercms.mdx index 828217063c916..216c3bb6fb41f 100644 --- a/src/content/docs/en/guides/cms/buttercms.mdx +++ b/src/content/docs/en/guides/cms/buttercms.mdx @@ -47,7 +47,7 @@ To get started, you will need to have the following:
```shell - pnpm install buttercms + pnpm add buttercms ``` diff --git a/src/content/docs/en/guides/cms/contentful.mdx b/src/content/docs/en/guides/cms/contentful.mdx index 491f8c5b2058c..21a2239f073e8 100644 --- a/src/content/docs/en/guides/cms/contentful.mdx +++ b/src/content/docs/en/guides/cms/contentful.mdx @@ -79,7 +79,7 @@ To connect with your Contentful space, install both of the following using the s ```shell - pnpm install contentful @contentful/rich-text-html-renderer + pnpm add contentful @contentful/rich-text-html-renderer ``` @@ -428,7 +428,7 @@ Navigate to http://localhost:4321/ and click on one of your posts to make sure y #### Server side rendering -If you've [opted in to SSR mode](/en/guides/server-side-rendering/#enabling-ssr-in-your-project), you will use a dynamic route that uses a `slug` parameter to fetch the data from Contentful. +If you've [opted in to SSR mode](/en/guides/server-side-rendering/), you will use a dynamic route that uses a `slug` parameter to fetch the data from Contentful. Create a `[slug].astro` page in `src/pages/posts`. Use [`Astro.params`](/en/reference/api-reference/#astroparams) to get the slug from the URL, then pass that to `getEntries`: diff --git a/src/content/docs/en/guides/cms/cosmic.mdx b/src/content/docs/en/guides/cms/cosmic.mdx new file mode 100644 index 0000000000000..41e78f15eb397 --- /dev/null +++ b/src/content/docs/en/guides/cms/cosmic.mdx @@ -0,0 +1,242 @@ +--- +title: Cosmic & Astro +description: Add content to your Astro project using Cosmic as a CMS +type: cms +service: Cosmic +i18nReady: true +--- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' + + + +[Cosmic](https://www.cosmicjs.com/) is a [headless CMS](https://www.cosmicjs.com/headless-cms) that provides an admin dashboard to manage content and an API that can integrate with a diverse range of frontend tools. + +## Prerequisites + +1. **An Astro project**- If you’d like to start with a fresh Astro project, read the [installation guide](/en/install/auto/). This guide follows a simplified version of the [Astro Headless CMS Theme](https://astro.build/themes/details/cosmic-cms-blog/) with [Tailwind CSS](https://tailwindcss.com/) for styling. +2. **A Cosmic account and Bucket** - [Create a free Cosmic account](https://app.cosmicjs.com/signup) if you don’t have one. After creating your account, you'll be prompted to create a new empty project. There's also a [Simple Astro Blog template](https://www.cosmicjs.com/marketplace/templates/simple-astro-blog) available (this is the same template as the Astro Headless CMS Theme) to automatically import all of the content used in this guide. +3. **Your Cosmic API keys** - From your Cosmic dasboard, you will need to locate both the **Bucket slug** and **Bucket read key** in order to connect to Cosmic. + +## Integrating Cosmic with Astro + + +### Installing Necessary Dependencies + +Add the [Cosmic JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk) to fetch data from your Cosmic Bucket. + + + + ```shell + npm install @cosmicjs/sdk + ``` + + + ```shell + pnpm add @cosmicjs/sdk + ``` + + + ```shell + yarn add @cosmicjs/sdk + ``` + + + +### Configuring API Keys + +Create a `.env` file at the root of your Astro project (if it does not already exist). Add both the **Bucket slug** and **Bucket read key** available from your Cosmic dashboard as public environment variables. + +```ini title=".env" +PUBLIC_COSMIC_BUCKET_SLUG=YOUR_BUCKET_SLUG +PUBLIC_COSMIC_READ_KEY=YOUR_READ_KEY +``` + +## Fetching Data from Cosmic + +1. Create a new file called `cosmic.js`. Place this file inside of the `src/lib` folder in your project. + +2. Add the following code to fetch data from Cosmic using the SDK and your environment variables. + + The example below creates a function called `getAllPosts()` to fetch metadata from Cosmic `posts` objects: + + ```js + // src/lib/cosmic.js + import { createBucketClient } from '@cosmicjs/sdk' + + const cosmic = createBucketClient({ + bucketSlug: import.meta.env.PUBLIC_COSMIC_BUCKET_SLUG, + readKey: import.meta.env.PUBLIC_COSMIC_READ_KEY + }) + + export async function getAllPosts() { + const data = await cosmic.objects + .find({ + type: 'posts' + }) + .props('title,slug,metadata,created_at') + return data.objects + } + ``` + + Read more about [queries in the Cosmic documentation](https://www.cosmicjs.com/docs/api/queries). + +3. Import your query function in a `.astro` component. After fetching data, the results from the query can be used in your Astro template. + + The following example shows fetching metadata from Cosmic `posts` and passing these values as props to a `` component to create a list of blog posts: + + ```astro + --- + // src/pages/index.astro + import Card from '../components/Card.astro' + import { getAllPosts } from '../lib/cosmic' + + const data = await getAllPosts() + --- + +
+
    + { + data.map((post) => ( + tag)} + /> + )) + } +
+
+ ``` + + [View source code for the Card component](https://github.com/cosmicjs/simple-astro-blog/blob/main/src/components/Card.astro) + +## Building a Blog with Astro and Cosmic + +You can manage your Astro blog's content using Cosmic and create webhooks to automatically redeploy your website when you update or add new content. + +### Cosmic Content Objects + +The following instructions assume that you have an **Object Type** in Cosmic called **posts**. Each individual blog post is a `post` that is defined in the Cosmic dashboard with the following Metafields: + +1. **Text input** - Author +2. **Image** - Cover Image +3. **Repeater** - Tags + - **Text input** - Title +4. **Text area** - Excerpt +5. **Rich Text** - Content + +### Displaying a List of Blog Posts in Astro + +Using the same [data-fetching method](#fetching-data-from-cosmic) as above, import the `getAllPosts()` query from your script file and await the data. This function provides metadata about each `post` which can be displayed dynamically. + +The example below passes these values to a `` component to display a formatted list of blog posts: + +```astro +--- +// src/pages/index.astro +import Card from '../components/Card.astro' +import { getAllPosts } from '../lib/cosmic' + +const data = await getAllPosts() +--- + +
+
    + { + data.map((post) => ( + tag)} + /> + )) + } +
+
+``` + +### Generating Individual Blog Posts with Astro + +To generate an individual page with full content for each blog post, create a [dynamic routing page](/en/core-concepts/routing/#dynamic-routes) at `src/pages/blog/[slug].astro`. + +This page will export a `getStaticPaths()` function to generate a page route at the `slug` returned from each `post` object. This function is called at build time and generates and renders all of your blog posts at once. + +To access your data from Cosmic: + +- Query Cosmic inside of `getStaticPaths()` to fetch data about each post and provide it to the function. +- Use each `post.slug` as a route parameter, creating the URLs for each blog post. +- Return each `post` inside of `Astro.props`, making the post data available to HTML template portion of the page component for rendering. + +The HTML markup below uses various data from Cosmic, such as the post title, cover image, and the **rich text content** (full blog post content). Use [set:html](/en/reference/directives-reference/#sethtml) on the element displaying the rich text content from Cosmic to render HTML elements on the page exactly as fetched from Cosmic. + +```astro +--- +// src/pages/blog/[slug].astro +import { getAllPosts } from '../../lib/cosmic' +import { Image } from 'astro:assets' + +export async function getStaticPaths() { + const data = (await getAllPosts()) || [] + + return data.map((post) => { + return { + params: { slug: post.slug }, + props: { post } + } + }) +} + +const { post } = Astro.props +--- + +
+
+

{post.title}

+
+ {post.metadata.author?.title} +
+ { + post.metadata.cover_image && ( + {`Cover + ) + } +
+
+``` + +### Publishing your site + +To deploy your website, visit the [deployment guides](/en/guides/deploy/) and follow the instructions for your preferred hosting provider. + +#### Rebuild on Cosmic content updates + +You can set up a webhook in Cosmic directly to trigger a redeploy of your site on your hosting platform (e.g. Vercel) whenever you update or add content Objects. + +Under "Settings" > "webhooks", add the URL endpoint from Vercel and select the Object Type you would like to trigger the webhook. Click “Add webhook” to save it. + +##### Netlify + +To set up a webhook in Netlify: + +1. Go to your site dashboard and click on **Build & deploy**. +2. Under the **Continuous Deployment** tab, find the **Build hooks** section and click on **Add build hook**. +3. Provide a name for your webhook and select the branch you want to trigger the build on. Click on **Save** and copy the generated URL. + +##### Vercel + +To set up a webhook in Vercel: + +1. Go to your project dashboard and click on **Settings**. +2. Under the **Git** tab, find the **Deploy Hooks** section. +3. Provide a name for your webhook and the branch you want to trigger the build on. Click **Add** and copy the generated URL. \ No newline at end of file diff --git a/src/content/docs/en/guides/cms/directus.mdx b/src/content/docs/en/guides/cms/directus.mdx index 4754077a8c897..669707acdee6e 100644 --- a/src/content/docs/en/guides/cms/directus.mdx +++ b/src/content/docs/en/guides/cms/directus.mdx @@ -10,7 +10,7 @@ i18nReady: false [Directus](https://directus.io/) is a backend-as-a-service which can be used to host data and content for your Astro project. ## Official Resources -- Check out the official guide, [Get Started Building an Astro Website with Directus](https://directus.io/guides/get-started-building-an-astro-website-with-directus/). + - Directus provides an [example Astro blog template](https://github.com/directus/examples/tree/main/astro). ## Community Resources diff --git a/src/content/docs/en/guides/cms/ghost.mdx b/src/content/docs/en/guides/cms/ghost.mdx index 71d2c3e1c266c..5c8c90d110a81 100644 --- a/src/content/docs/en/guides/cms/ghost.mdx +++ b/src/content/docs/en/guides/cms/ghost.mdx @@ -68,7 +68,7 @@ To connect with Ghost, install the official content API wrapper [`@tryghost/cont
```shell - pnpm install @tryghost/content-api + pnpm add @tryghost/content-api ``` diff --git a/src/content/docs/en/guides/cms/keystatic.mdx b/src/content/docs/en/guides/cms/keystatic.mdx index ceab6817dc87d..1b2cb6bee8133 100644 --- a/src/content/docs/en/guides/cms/keystatic.mdx +++ b/src/content/docs/en/guides/cms/keystatic.mdx @@ -14,16 +14,30 @@ import Aside from '~/components/Aside.astro' :::tip If you're starting a **new Astro + Keystatic project from scratch**, you can use the [Keystatic CLI](https://keystatic.com/docs/quick-start#keystatic-cli) to generate a new project in seconds: -```bash -npm create @keystatic@latest -``` + + + ```shell + npm create @keystatic@latest + ``` + + + ```shell + pnpm create @keystatic@latest + ``` + + + ```shell + yarn create @keystatic + ``` + + Select the Astro template, and you'll be ready to [deploy](#deploying-keystatic--astro)! ::: ## Prerequisites -- An existing Astro project [with server-side rendering (SSR) and `output: 'hybrid'` configured](/en/guides/server-side-rendering/#enabling-ssr-in-your-project). +- An existing Astro project [with server-side rendering (SSR) and `output: 'hybrid'` configured](/en/guides/server-side-rendering/). :::note If you intend to sync Keystatic's data with GitHub, you will also need **a GitHub account with `write` permissions** on the repository for this project. @@ -61,7 +75,7 @@ You will also need two Keystatic packages: ```shell - pnpm install @keystatic/core @keystatic/astro + pnpm add @keystatic/core @keystatic/astro ``` @@ -71,6 +85,25 @@ You will also need two Keystatic packages: +## Adding the Astro integration + +Add the Astro integration from `@keystatic/astro` in your Astro config file: + +```js ins={6} ins=", keystatic()" +// astro.config.mjs +import { defineConfig } from 'astro/config' + +import react from '@astrojs/react' +import markdoc from '@astrojs/markdoc' +import keystatic from '@keystatic/astro' + +// https://astro.build/config +export default defineConfig({ + integrations: [react(), markdoc(), keystatic()], + output: 'hybrid', +}) +``` + ## Creating a Keystatic config file A Keystatic config file is required to define your content schema. This file will also allow you to connect a project to a specific GitHub repository (if you decide to do so). @@ -113,55 +146,15 @@ If you are already using [content collections](/en/guides/content-collections/#d Keystatic is now configured to manage your content based on your schema. -## Setting up the Keystatic Admin UI dashboard - -The Keystatic Admin UI is a React app that runs in your Astro project. - -The following steps will create a dashboard that lives in `src/pages/keystatic/` for managing your site content. - -1. Create a `keystatic.page.ts` in the project root, alongside your Keystatic config file. - - ```ts - // keystatic.page.ts - import { makePage } from '@keystatic/astro/ui' - import keystaticConfig from './keystatic.config' - - export const Keystatic = makePage(keystaticConfig) - ``` - -2. Create a new page called `src/pages/keystatic/[...params].astro` and mount the component on the client side only: - - ```astro - --- - // src/pages/keystatic/[...params].astro - import { Keystatic } from '../../../keystatic.page' - export const prerender = false - --- - - - ``` - -3. Create a new file called `src/pages/api/keystatic/[...params].ts` that will create `API routes` for Keystatic's Admin UI. - - ```jsx - // src/pages/api/keystatic/[...params].ts - import { makeHandler } from '@keystatic/astro/api' - import keystaticConfig from '../../../../keystatic.config' - - export const all = makeHandler({ - config: keystaticConfig, - }) - - export const prerender = false - ``` +## Running Keystatic locally -4. To launch your Keystatic Admin UI dashboard, start Astro's dev server: +To launch your Keystatic Admin UI dashboard, start Astro's dev server: ```bash npm run dev ``` -5. Visit `http://127.0.0.1:4321/keystatic` in the browser to see the Keystatic Admin UI running. +Visit `http://127.0.0.1:4321/keystatic` in the browser to see the Keystatic Admin UI running. ## Creating a new post diff --git a/src/content/docs/en/guides/cms/kontent-ai.mdx b/src/content/docs/en/guides/cms/kontent-ai.mdx index ee79374e5457c..97a0fb561dc76 100644 --- a/src/content/docs/en/guides/cms/kontent-ai.mdx +++ b/src/content/docs/en/guides/cms/kontent-ai.mdx @@ -64,7 +64,7 @@ To connect Astro with your Kontent.ai project, install the [Kontent.ai TypeScrip ```shell - pnpm install @kontent-ai/delivery-sdk + pnpm add @kontent-ai/delivery-sdk ``` @@ -206,7 +206,7 @@ First, install the [Kontent.ai JS model generator](https://github.com/kontent-ai ```shell - pnpm install @kontent-ai/model-generator ts-node dotenv + pnpm add @kontent-ai/model-generator ts-node dotenv ``` diff --git a/src/content/docs/en/guides/cms/storyblok.mdx b/src/content/docs/en/guides/cms/storyblok.mdx index 4c67c7838fc4e..b01bfd3903f10 100644 --- a/src/content/docs/en/guides/cms/storyblok.mdx +++ b/src/content/docs/en/guides/cms/storyblok.mdx @@ -58,7 +58,7 @@ To connect Astro with your Storyblok space, install the official [Storyblok inte ```shell - pnpm install @storyblok/astro vite + pnpm add @storyblok/astro vite ``` @@ -270,7 +270,7 @@ To connect your newly created Bloks to Astro components, create a new folder nam ```astro title="src/storyblok/Page.astro" --- import { storyblokEditable } from '@storyblok/astro' -import StoryblokComponent from '@storyblok/astro/StoryblokComponent.astro' +import StoryblokComponent from '@storyblok/astro/components/StoryblokComponent'; const { blok } = Astro.props --- @@ -451,7 +451,7 @@ When adding folders inside of Storyblok, include them in the slug when interacti #### Server-side rendering -If you’ve [opted into SSR mode](/en/guides/server-side-rendering/#enabling-ssr-in-your-project), you will use dynamic routes to fetch the page data from Storyblok. +If you’ve [opted into SSR mode](/en/guides/server-side-rendering/), you will use dynamic routes to fetch the page data from Storyblok. Create a new directory `src/pages/blog/` and add a new file called `[...slug].astro` with the following code: diff --git a/src/content/docs/en/guides/cms/strapi.mdx b/src/content/docs/en/guides/cms/strapi.mdx index 37e361287fd2a..d47aff2b3590f 100644 --- a/src/content/docs/en/guides/cms/strapi.mdx +++ b/src/content/docs/en/guides/cms/strapi.mdx @@ -318,7 +318,7 @@ Make sure to choose the right rendering for your content. For markdown check out #### Server-side rendering -If you've [opted into SSR mode](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) with `output: server` or `output: hybrid`, [generate your dynamic routes](/en/core-concepts/routing/#server-ssr-mode) using the following code: +If you've [opted into SSR mode](/en/guides/server-side-rendering/) with `output: server` or `output: hybrid`, [generate your dynamic routes](/en/core-concepts/routing/#server-ssr-mode) using the following code: Create the `src/pages/blog/[slug].astro` file: diff --git a/src/content/docs/en/guides/cms/tina-cms.mdx b/src/content/docs/en/guides/cms/tina-cms.mdx index b2875f417c70b..3d0ab8a6b546c 100644 --- a/src/content/docs/en/guides/cms/tina-cms.mdx +++ b/src/content/docs/en/guides/cms/tina-cms.mdx @@ -12,7 +12,7 @@ import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' ## Integrating with Astro -To get started, you'll need an existing Astro project. +To get started, you'll need an existing Astro project. 1. Run the following command to install Tina into your Astro project. @@ -38,8 +38,8 @@ To get started, you'll need an existing Astro project. - When prompted "What framework are you using", choose **Other**. - When asked where public assets are stored, press Enter. - After this has finished, you should now have a `.tina` folder in the root of your project and an `admin` folder in your public directory. It will also create a Markdown file at `content/posts/hello-world.md`. - + After this has finished, you should now have a `.tina` folder in the root of your project and a generated `hello-world.md` file at `content/posts`. + 2. Change the `dev` script in `package.json`: @@ -49,7 +49,7 @@ To get started, you'll need an existing Astro project. { "scripts": { "dev": "astro dev", - "dev": "tinacms dev -c 'astro dev'" + "dev": "tinacms dev -c \"astro dev\"" } } ``` @@ -60,7 +60,7 @@ To get started, you'll need an existing Astro project. { "scripts": { "dev": "astro dev", - "dev": "tinacms dev -c 'astro dev'" + "dev": "tinacms dev -c \"astro dev\"" } } ``` @@ -71,7 +71,7 @@ To get started, you'll need an existing Astro project. { "scripts": { "dev": "astro dev", - "dev": "tinacms dev -c 'astro dev'" + "dev": "tinacms dev -c \"astro dev\"" } } ``` @@ -132,7 +132,7 @@ To get started, you'll need an existing Astro project. name: "body", label: "Body", isBody: true, - }, + }, ], }, ], @@ -148,7 +148,7 @@ To get started, you'll need an existing Astro project. - [TinaCMS Astro integration guide](https://tina.io/docs/frameworks/astro/). -## Community Resources +## Community Resources - [Astro Tina Starter with visual editing](https://github.com/dawaltconley/tina-astro) by Jeff See + Dylan Awalt-Conley - [Astro Tina Starter with basic editing](https://github.com/tombennet/astro-tina-starter/tree/main) by Tom Bennet diff --git a/src/content/docs/en/guides/cms/wordpress.mdx b/src/content/docs/en/guides/cms/wordpress.mdx index 1c527b5d5aeb8..07b2570684adb 100644 --- a/src/content/docs/en/guides/cms/wordpress.mdx +++ b/src/content/docs/en/guides/cms/wordpress.mdx @@ -175,8 +175,8 @@ To deploy your site visit our [deployment guides](/en/guides/deploy/) and follow - [Building An Astro Website With WordPress As A Headless CMS](https://blog.openreplay.com/building-an-astro-website-with-wordpress-as-a-headless-cms/) by Chris Bongers. - [Building with Astro x WordPress](https://www.youtube.com/watch?v=Jstqgklvfnc) on Ben Holmes's stream. -- [Building a Headless WordPress Site with Astro](https://developers.wpengine.com/blog/building-a-headless-wordpress-site-with-astro) by Jeff Everhart -- [Astro and WordPress as an API](https://darko.io/posts/wp-as-an-api/) +- [Building a Headless WordPress Site with Astro](https://developers.wpengine.com/blog/building-a-headless-wordpress-site-with-astro) by Jeff Everhart. +- [Astro and WordPress as an API](https://darko.io/posts/wp-as-an-api/) by Darko Bozhinovski. ## Production Sites diff --git a/src/content/docs/en/guides/configuring-astro.mdx b/src/content/docs/en/guides/configuring-astro.mdx index 8ce5548b85dd3..1e23000db0cb4 100644 --- a/src/content/docs/en/guides/configuring-astro.mdx +++ b/src/content/docs/en/guides/configuring-astro.mdx @@ -115,7 +115,8 @@ export default defineConfig({ ``` :::note -Vite-specific `import.meta` properties, like `import.meta.env` or `import.meta.glob`, are _not_ accessible from your configuration file. We recommend alternatives like [dotenv](https://github.com/motdotla/dotenv) or [fast-glob](https://github.com/mrmlnc/fast-glob) for these respective use cases. +{/* Need to use here because Vite does an auto-replace on import-meta-env that breaks rendering */} +Vite-specific `import.meta` properties, like {'import.meta.env'} or `import.meta.glob`, are _not_ accessible from your configuration file. We recommend alternatives like [dotenv](https://github.com/motdotla/dotenv) or [fast-glob](https://github.com/mrmlnc/fast-glob) for these respective use cases. ::: ## Customising Output Filenames @@ -153,7 +154,7 @@ You can also use [Vite's `loadEnv` helper](https://main.vitejs.dev/config/#using :::note `pnpm` does not allow you to import modules that are not directly installed in your project. If you are using `pnpm`, you will need to install `vite` to use the `loadEnv` helper. ```sh -pnpm install vite --save-dev +pnpm add vite --save-dev ``` ::: diff --git a/src/content/docs/en/guides/content-collections.mdx b/src/content/docs/en/guides/content-collections.mdx index 01312407e9829..10011a799e49f 100644 --- a/src/content/docs/en/guides/content-collections.mdx +++ b/src/content/docs/en/guides/content-collections.mdx @@ -7,8 +7,8 @@ i18nReady: true --- import FileTree from '~/components/FileTree.astro' import Since from '~/components/Since.astro' -import TypeScriptSettingTabs from '~/components/tabs/TypeScriptSettingTabs.astro' import RecipeLinks from "~/components/RecipeLinks.astro" +import Badge from "~/components/Badge.astro"

@@ -542,6 +542,21 @@ If you have an existing Astro project, such as a blog, that uses Markdown or MDX See how to convert a basic blog example from `src/pages/posts/` to `src/content/posts` in our [step-by-step tutorial](/en/tutorials/add-content-collections/) that uses the codebase from [the Build a Blog tutorial's finished project](https://github.com/withastro/blog-tutorial-demo). +## Enabling Build Caching + +

Experimental

+ +If you are working with large collections, you may wish to enable cached builds with the [`experimental.contentCollectionCache`](/en/reference/configuration-reference/#experimentalcontentcollectioncache) flag. This experimental feature optimizes Astro's build process, enabling unchanged collections to be stored and reused between builds. + +In many cases, this can lead to significant build performance improvements. + +While this feature stabilizes, you may run into issues with the stored cache. You can always reset your build cache by running the following command: + +``` +npm run astro build -- --force +``` + + ## Modifying Frontmatter with Remark :::caution @@ -561,4 +576,40 @@ const { remarkPluginFrontmatter } = await blogPost.render(); -The remark and rehype pipelines only run when your content is rendered, which explains why `remarkPluginFrontmatter` is only available after you call `render()` on your content entry. In contrast, `getCollection()` and `getEntry()` cannot return these values directly because they do not render your content. \ No newline at end of file +The remark and rehype pipelines only run when your content is rendered, which explains why `remarkPluginFrontmatter` is only available after you call `render()` on your content entry. In contrast, `getCollection()` and `getEntry()` cannot return these values directly because they do not render your content. + +## Working with dates in the frontmatter + +Several date formats are possible in content collections, but your collection's schema must match the format used in your Markdown or MDX YAML frontmatter. + +YAML uses the [ISO-8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard to express dates. Use the format `yyyy-mm-dd` (e.g. `2021-07-28`) along with a schema type of `z.date()`: + +```markdown title="src/pages/posts/example-post.md" +--- +title: My Blog Post +pubDate: 2021-07-08 +--- +``` + +The date format will be specified in UTC if a timezone is not provided. If you need to specify a timezone, you can use the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + +```markdown title="src/pages/posts/example-post.md" +--- +title: My Blog Post +pubDate: 2021-07-08T12:00:00-04:00 +--- +``` + +To render only the `YYYY-MM-DD` from the full UTC timestamp, use the JavaScript `slice` method to remove the timestamp: + +```astro title="src/layouts/ExampleLayout.astro" +--- +const { frontmatter } = Astro.props; +--- +

{frontmatter.title}

+

{frontmatter.pubDate.slice(0,10)}

+``` +To see an example of using `toLocaleDateString` to format the day, month, and year instead, see the [`` component](https://github.com/withastro/astro/blob/latest/examples/blog/src/components/FormattedDate.astro) in the official Astro blog template. + + + diff --git a/src/content/docs/en/guides/deploy.mdx b/src/content/docs/en/guides/deploy.mdx index b646ebba30d7b..1882f64befca8 100644 --- a/src/content/docs/en/guides/deploy.mdx +++ b/src/content/docs/en/guides/deploy.mdx @@ -78,7 +78,7 @@ By default, the build output will be placed at `dist/`. This location can be cha :::note Before deploying your Astro site with [SSR (server-side rendering)](/en/guides/server-side-rendering/) enabled, make sure you have: -- Installed the [appropriate adapter](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) to your project dependencies (either manually, or using the adapter's `astro add` command, e.g. `npx astro add netlify`). +- Installed the [appropriate adapter](/en/guides/server-side-rendering/) to your project dependencies (either manually, or using the adapter's `astro add` command, e.g. `npx astro add netlify`). - [Added the adapter](/en/reference/configuration-reference/#integrations) to your `astro.config.mjs` file's import and default export when installing manually. (The `astro add` command will take care of this step for you!) ::: diff --git a/src/content/docs/en/guides/deploy/cloudflare.mdx b/src/content/docs/en/guides/deploy/cloudflare.mdx index 6cb0520dd1d63..5fd5ed3d88ad3 100644 --- a/src/content/docs/en/guides/deploy/cloudflare.mdx +++ b/src/content/docs/en/guides/deploy/cloudflare.mdx @@ -60,7 +60,7 @@ After your assets are uploaded, Wrangler will give you a preview URL to inspect For the preview to work, you must install `wrangler` ```bash -pnpm install wrangler --save-dev +pnpm add wrangler --save-dev ``` It's then possible to update the preview script to run `wrangler` instead of Astro’s built-in preview command: diff --git a/src/content/docs/en/guides/deploy/github.mdx b/src/content/docs/en/guides/deploy/github.mdx index 28f750e1c91bb..71affbe330dac 100644 --- a/src/content/docs/en/guides/deploy/github.mdx +++ b/src/content/docs/en/guides/deploy/github.mdx @@ -29,7 +29,8 @@ Astro maintains the official `withastro/action` to deploy your project with very :::note Don't set a `base` parameter if: - - Your repository is named `.github.io`. + - Your page is served from the root folder. + - Your repository is located at `https://github.com//.github.io`. - You're using a custom domain. ::: diff --git a/src/content/docs/en/guides/deploy/gitlab.mdx b/src/content/docs/en/guides/deploy/gitlab.mdx index 607dca2b06260..b9147410bb329 100644 --- a/src/content/docs/en/guides/deploy/gitlab.mdx +++ b/src/content/docs/en/guides/deploy/gitlab.mdx @@ -14,7 +14,8 @@ Check out [the official GitLab Pages Astro example project](https://gitlab.com/p ## How to deploy 1. Set the correct `site` in `astro.config.mjs`. -2. Set `outDir:public` in `astro.config.mjs`. This setting instructs Astro to put the static build output in a folder called `public`, which is the folder required by GitLab Pages for exposed files. +2. Rename the `public/` directory to `static`. +3. Set `outDir:public` in `astro.config.mjs`. This setting instructs Astro to put the static build output in a folder called `public`, which is the folder required by GitLab Pages for exposed files. If you were using the [`public/` directory](/en/core-concepts/project-structure/#public) as a source of static files in your Astro project, rename it and use that new folder name in `astro.config.mjs` for the value of `publicDir`. @@ -24,26 +25,25 @@ Check out [the official GitLab Pages Astro example project](https://gitlab.com/p import { defineConfig } from 'astro/config'; export default defineConfig({ - sitemap: true, - site: 'https://astro.build/', + site: 'https://.gitlab.io', + base: '/' outDir: 'public', publicDir: 'static', }); ``` -3. Create a file called `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content: +4. Create a file called `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content: ```yaml - # The Docker image that will be used to build your app - image: node:lts - pages: - cache: - paths: - - node_modules/ + # The Docker image that will be used to build your app + image: node:lts + + before_script: + - npm ci + script: # Specify the steps involved to build your app here - - npm install - npm run build artifacts: diff --git a/src/content/docs/en/guides/deploy/microsoft-azure.mdx b/src/content/docs/en/guides/deploy/microsoft-azure.mdx index 1b6e1e322c879..1095cb05d9307 100644 --- a/src/content/docs/en/guides/deploy/microsoft-azure.mdx +++ b/src/content/docs/en/guides/deploy/microsoft-azure.mdx @@ -7,8 +7,9 @@ i18nReady: true [Azure](https://azure.microsoft.com/) is a cloud platform from Microsoft. You can deploy your Astro site with Microsoft Azure’s [Static Web Apps](https://aka.ms/staticwebapps) service. -## Prerequisites +This guide takes you through deploying your Astro site stored in GitHub using Visual Studio Code. Please see Microsoft guides for using an [Azure Pipelines Task](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/azure-static-web-app-v0?view=azure-pipelines) for other setups. +## Prerequisites To follow this guide, you will need: - An Azure account and a subscription key. You can create a [free Azure account here](https://azure.microsoft.com/free). @@ -21,6 +22,23 @@ To follow this guide, you will need: 2. Open the Static Web Apps extension, sign in to Azure, and click the **+** button to create a new Static Web App. You will be prompted to designate which subscription key to use. -3. Follow the wizard started by the extension to give your app a name, choose a framework preset, and designate the app root (usually `/`) and built file location `/dist`. The wizard will run and will create a [GitHub Action](https://github.com/features/actions) in the `.github` folder of your repo. (This folder will be automatically created if it does not already exist.) +3. Follow the wizard started by the extension to give your app a name, choose a framework preset, and designate the app root (usually `/`) and built file location (use `/dist`). Astro is not listed in the built-in templates in Azure so you will need to select `custom`. The wizard will run and will create a [GitHub Action](https://github.com/features/actions) in the `.github` folder of your repo. (This folder will be automatically created if it does not already exist.) The GitHub Action will deploy your app (you can see its progress in your repo’s Actions tab on GitHub). When successfully completed, you can view your app at the address shown in the SWA Extension’s progress window by clicking the **Browse Website** button (this will appear after the GitHub Action has run). + +## Known Issues +The GitHub action yaml that is created for you assumes the use of node 14. This means the Astro build fails. To resolve this update your projects package.json file with this snippet. + +``` + "engines": { + "node": ">=18.0.0" + }, +``` + +## Official Resources + +- [Microsoft Azure Static Web Apps documentation](https://learn.microsoft.com/en-us/azure/static-web-apps/) + +## Community Resources + +- [Deploying an Astro Website to Azure Static Web Apps](https://www.blueboxes.co.uk/deploying-an-astro-website-to-azure-static-web-apps) diff --git a/src/content/docs/en/guides/environment-variables.mdx b/src/content/docs/en/guides/environment-variables.mdx index edfcd84c1d617..a11b906bffbe5 100644 --- a/src/content/docs/en/guides/environment-variables.mdx +++ b/src/content/docs/en/guides/environment-variables.mdx @@ -96,7 +96,8 @@ const data = fetch(`${import.meta.env.PUBLIC_POKEAPI}/pokemon/squirtle`); ``` :::caution -Because Vite statically replaces `import.meta.env`, you cannot access it with dynamic keys like `import.meta.env[key]`. +{/* Need to use here because Vite does an auto-replace on import-meta-env that breaks rendering */} +Because Vite statically replaces {'import.meta.env'}, you cannot access it with dynamic keys like {'import.meta.env[key]'}. ::: When using SSR, environment variables can be accessed at runtime based on the SSR adapter being used. With most adapters you can access environment variables with `process.env`, but some adapters work differently. For the Deno adapter, you will use `Deno.env.get()`. See how to [access the Cloudflare runtime](/en/guides/integrations-guide/cloudflare/#cloudflare-runtime) to handle environment variables when using the Cloudflare adapter. Astro will first check the server environment for variables, and if they don't exist, Astro will look for them in .env files. diff --git a/src/content/docs/en/guides/fonts.mdx b/src/content/docs/en/guides/fonts.mdx index a7b93b4176292..a0e68a09181ea 100644 --- a/src/content/docs/en/guides/fonts.mdx +++ b/src/content/docs/en/guides/fonts.mdx @@ -60,7 +60,7 @@ The [Fontsource](https://fontsource.org/) project simplifies using Google Fonts
```shell - pnpm install @fontsource/twinkle-star + pnpm add @fontsource/twinkle-star ``` diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index a4a2c123f3274..6553616986c73 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -6,6 +6,7 @@ i18nReady: true import Since from '~/components/Since.astro'; import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; import Badge from '~/components/Badge.astro'; +import RecipeLinks from "~/components/RecipeLinks.astro"; Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to from an external URL, or managed in a CMS or CDN! @@ -609,6 +610,8 @@ import stars from "~/stars/docline.png"; The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/core-concepts/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `` component. + + `getImage()` takes an options object with the [same properties as the Image component](#properties) (except `alt`). ```astro @@ -649,6 +652,16 @@ If the image is merely decorative (i.e. doesn’t contribute to the understandin [Sharp](https://github.com/lovell/sharp) is the default image service used for `astro:assets`. +:::note +When using a [strict package manager](https://pnpm.io/pnpm-vs-npm#npms-flat-tree) like `pnpm`, you may need to manually install Sharp into your project even though it is an Astro dependency: + +```bash +pnpm install sharp +``` +::: + +### Configure Squoosh + If you would prefer to use [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images, update your config with the following: ```js title="astro.config.mjs" ins={4-6} @@ -661,13 +674,21 @@ export default defineConfig({ }); ``` -:::note -When using a [strict package manager](https://pnpm.io/pnpm-vs-npm#npms-flat-tree) like `pnpm`, you may need to manually install Sharp into your project even though it is an Astro dependency: +### Configure no-op passthrough service -```bash -pnpm install sharp +If your [adapter for `server` or `hybrid` mode](https://astro.build/integrations/?search=&categories%5B%5D=adapters) does not support Astro's built-in Squoosh and Sharp image optimization (e.g. Deno, Cloudflare), you can configure a no-op image service to allow you to use the `` and `` components. Note that Astro does not perform any image transformation and processing in these environments. However, you can still enjoy the other benefits of using `astro:assets`, including no Cumulative Layout Shift (CLS), the enforced `alt` attribute, and a consistent authoring experience. + +Configure the `passthroughImageService()` to avoid both Squoosh and Sharp image processing: + +```js title="astro.config.mjs" ins={4-6} "passthroughImageService" +import { defineConfig, passthroughImageService } from 'astro/config'; + +export default defineConfig({ + image: { + service: passthroughImageService() + } +}); ``` -::: ## Community Integrations diff --git a/src/content/docs/en/guides/imports.mdx b/src/content/docs/en/guides/imports.mdx index 6f8c73a758c3d..d2762f22d8a65 100644 --- a/src/content/docs/en/guides/imports.mdx +++ b/src/content/docs/en/guides/imports.mdx @@ -217,7 +217,7 @@ Astro supports loading WASM files directly into your application using the brows ## Node Builtins -We encourage Astro users to avoid Node.js builtins (`fs`, `path`, etc.) whenever possible. Astro is compatible with multiple runtimes using [adapters](/en/guides/server-side-rendering/#adding-an-adapter). This includes [Deno](https://github.com/denoland/deno-astro-adapter) and [Cloudflare Workers](/en/guides/integrations-guide/cloudflare/) which do not support Node builtin modules such as `fs`. +We encourage Astro users to avoid Node.js builtins (`fs`, `path`, etc.) whenever possible. Astro is compatible with multiple runtimes using [adapters](/en/guides/server-side-rendering/). This includes [Deno](https://github.com/denoland/deno-astro-adapter) and [Cloudflare Workers](/en/guides/integrations-guide/cloudflare/) which do not support Node builtin modules such as `fs`. Our aim is to provide Astro alternatives to common Node.js builtins. However, no such alternatives exist today. So, if you _really_ need to use these builtin modules we don't want to stop you. Astro supports Node.js builtins using Node’s newer `node:` prefix. If you want to read a file, for example, you can do so like this: diff --git a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx index f446943ada6f0..1c9c6170e6504 100644 --- a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx @@ -207,17 +207,25 @@ export default defineConfig({ ### `runtime` -`runtime: "off" | "local"` +`runtime: { mode: "off" | "local", persistTo: string }` -default `"off"` +default `{ mode: 'off', persistTo: '' }` Determines whether and how the Cloudflare Runtime is added to `astro dev`. The Cloudflare Runtime includes [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Read more about [accessing the Cloudflare Runtime](#cloudflare-runtime). +The `mode` property defines how the runtime is added to `astro dev`: + * `local`: uses bindings mocking and locally static placeholders * `off`: no access to the Cloudflare runtime using `astro dev`. You can alternatively use [Preview with Wrangler](#preview-with-wrangler) +The `persistTo` property defines where the local runtime is persisted to when using `mode: local`. This value is a directory relative to your `astro dev` execution path. + +The default value is set to `.wrangler/state/v3` to match the default path Wrangler uses. This means both tools are able to access and use the local state. + +Whichever directory is set in `persistTo`, `.wrangler` or your custom value, must be added to `.gitignore`. + ```diff lang="js" // astro.config.mjs import { defineConfig } from 'astro/config'; @@ -226,7 +234,7 @@ import cloudflare from '@astrojs/cloudflare'; export default defineConfig({ output: 'server', adapter: cloudflare({ -+ runtime: 'local', ++ runtime: { mode: 'local' }, }), }); ``` diff --git a/src/content/docs/en/guides/integrations-guide/deno.mdx b/src/content/docs/en/guides/integrations-guide/deno.mdx index 84b786e7af0aa..4658062bee9c0 100644 --- a/src/content/docs/en/guides/integrations-guide/deno.mdx +++ b/src/content/docs/en/guides/integrations-guide/deno.mdx @@ -8,4 +8,4 @@ The Deno adapter allows Astro to deploy your SSR site to Deno targets including The Deno adapter was previously maintained by Astro but now is maintained by Deno directly. Usage is now documented [in the Deno adapter repository](https://github.com/denoland/deno-astro-adapter). -If you are currently using this Astro adapter, you will need to migrate to the new Deno version or to [add another adapter](/en/guides/server-side-rendering/#adding-an-adapter) to continue using SSR in your project. +If you are currently using this Astro adapter, you will need to migrate to the new Deno version or to [add another adapter](/en/guides/server-side-rendering/) to continue using SSR in your project. diff --git a/src/content/docs/en/guides/integrations-guide/markdoc.mdx b/src/content/docs/en/guides/integrations-guide/markdoc.mdx index 83334cb700b0d..c1edabb625521 100644 --- a/src/content/docs/en/guides/integrations-guide/markdoc.mdx +++ b/src/content/docs/en/guides/integrations-guide/markdoc.mdx @@ -471,6 +471,40 @@ To achieve a more Markdown-like experience, where HTML elements can be included When `allowHTML` is enabled, HTML markup inside Markdoc documents will be rendered as actual HTML elements (including ` +``` + +You can additionally configure the priority of prefetching by passing the `with` option: + +```js +// Prefetch with `fetch()`, which has a higher priority. +prefetch('/about', { with: 'fetch' }); + +// Prefetch with ``, which has a lower priority +// and manually scheduled by the browser. (default) +prefetch('/about', { with: 'link' }); +``` + +The `prefetch()` API includes the same [data saver mode](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) and [slow connection](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType) detection, so that it only prefetches when needed. + +Make sure to only import `prefetch()` in client-side scripts as it relies on browser APIs. + +## Using with View Transitions + +When you use [View Transitions](/en/guides/view-transitions/) on a page, prefetching will also be enabled by default. It sets a default configuration of `{ prefetchAll: true }` which enables [prefetching for all links](#prefetch-all-links-by-default) on the page. + +You can customize the prefetch configuration in `astro.config.js` to override the default. For example: + +```js title="astro.config.js" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + // Disable prefetch completely + prefetch: false +}) +``` + +```js title="astro.config.js" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + // Keep prefetch, but only prefetch for links with `data-astro-prefetch` + prefetch: { + prefetchAll: false + } +}) +``` + +## Migrating from `@astrojs/prefetch` + +The `@astrojs/prefetch` integration was deprecated in v3.5.0 and will eventually be removed entirely. Use the following instructions to migrate to Astro's built-in prefetching which replaces this integration. + +1. Remove the `@astrojs/prefetch` integration and enable the `prefetch` config in `astro.config.js`: + + ```js title="astro.config.js" ins={6} del={2,5} + import { defineConfig } from 'astro/config'; + import prefetch from '@astrojs/prefetch'; + + export default defineConfig({ + integrations: [prefetch()], + prefetch: true + }) + ``` + +2. Convert from `@astrojs/prefetch`'s configuration options: + + - The deprecated integration used the `selector` config option to specify which links should be prefetched upon entering the viewport. + + Add `data-astro-prefetch="viewport"` to these individual links instead. + + ```html + + ``` + + - The deprecated integration used the `intentSelector` config option to specify which links should be prefetched when they were hovered over or focused. + + Add `data-astro-prefetch` or `data-astro-prefetch="hover"` to these individual links instead: + + ```html + + + + + + ``` + + - The `throttles` option from `@astrojs/prefetch` is no longer needed as the new prefetch feature will automatically schedule and prefetch optimally. diff --git a/src/content/docs/en/guides/rss.mdx b/src/content/docs/en/guides/rss.mdx index 09340fe1ddcbd..2205ad377e880 100644 --- a/src/content/docs/en/guides/rss.mdx +++ b/src/content/docs/en/guides/rss.mdx @@ -12,7 +12,7 @@ Astro supports fast, automatic RSS feed generation for blogs and other content w ## Setting up `@astrojs/rss` -The package [`@astrojs/rss`](https://github.com/withastro/astro/tree/main/packages/astro-rss) provides helpers for generating RSS feeds using [API endpoints](/en/core-concepts/endpoints/#static-file-endpoints). This unlocks both static builds _and_ on-demand generation when using an [SSR adapter](/en/guides/server-side-rendering/#adding-an-adapter). +The package [`@astrojs/rss`](https://github.com/withastro/astro/tree/main/packages/astro-rss) provides helpers for generating RSS feeds using [API endpoints](/en/core-concepts/endpoints/#static-file-endpoints). This unlocks both static builds _and_ on-demand generation when using an [SSR adapter](/en/guides/server-side-rendering/). 1. Install `@astrojs/rss` using your preferred package manager: @@ -24,7 +24,7 @@ The package [`@astrojs/rss`](https://github.com/withastro/astro/tree/main/packag ```shell - pnpm install @astrojs/rss + pnpm add @astrojs/rss ``` diff --git a/src/content/docs/en/guides/server-side-rendering.mdx b/src/content/docs/en/guides/server-side-rendering.mdx index b547079d548f5..313dc09edec2f 100644 --- a/src/content/docs/en/guides/server-side-rendering.mdx +++ b/src/content/docs/en/guides/server-side-rendering.mdx @@ -1,46 +1,66 @@ --- -title: Server-side Rendering +title: On-demand Rendering Adapters i18nReady: true --- import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import Since from '~/components/Since.astro'; +import RecipeLinks from '~/components/RecipeLinks.astro'; -Server-side rendering (SSR) refers to generating HTML pages on the server on-demand and sending them to the client. +Astro allows you to choose **on-demand rendering** for some, or all of your pages and endpoints. This is also known as **server-side rendering (SSR)**: generating HTML pages on the server when requested and sending them to the client. An **adapter** is used to run your project on the server and handle these requests. -SSR allows you to: +This on-demand rendering allows you to: - Implement sessions for login state in your app. -- Render data from an API called dynamically with `fetch`. +- Render data from an API called dynamically with `fetch()`. - Deploy your site to a host using an *adapter*. -Consider enabling server-side rendering in your Astro project if you need the following: +Consider enabling on-demand server rendering in your Astro project if you need the following: -- **API endpoints**: SSR enables you to create specific pages that function as API endpoints for tasks like database access, authentication, and authorization while keeping sensitive data hidden from the client. +- **API endpoints**: Create specific pages that function as API endpoints for tasks like database access, authentication, and authorization while keeping sensitive data hidden from the client. -- **Protected pages**: If you need to restrict access to a page based on user privileges, you can enable SSR to handle user access on the server. +- **Protected pages**: Restrict access to a page based on user privileges, by handling user access on the server. -- **Frequently changing content**: Enabling SSR lets you generate individual pages without requiring a static rebuild of your site. This is useful when the content of a page updates frequently. +- **Frequently changing content**: Generate individual pages without requiring a static rebuild of your site. This is useful when the content of a page updates frequently. -## Enabling SSR in Your Project +## Enable on-demand server rendering -To enable SSR features for production deployments, update your `output` configuration to `'server'` or `'hybrid'` (introduced in **v2.6.0**). Both of these modes control which [pages](/en/core-concepts/astro-pages/) or [server endpoints](/en/core-concepts/endpoints/#server-endpoints-api-routes) should be server-rendered. Each configuration option has a different default behavior, and allows individual routes to opt-out of the default accordingly: +Both of Astro's on-demand rendering output modes (`server` and `hybrid`) allow you to take advantage of static site performance by pre-rendering individual routes whenever possible, whether you have an entirely dynamic app or a mostly static site that needs on-demand rendering only for select routes. -- __`output: 'server'`__: Server-rendered by default. Use this when most or all of your site should be server-rendered. Any individual page or endpoint can *opt-in* to pre-rendering. +To decide which one to use in your project, choose the `output` option that represents how **most** of your pages and routes will be rendered: - ```js ins={6,7} - // astro.config.mjs - import { defineConfig } from 'astro/config'; - import nodejs from '@astrojs/node'; +- __`output: 'server'`__: On-demand rendered by default. Use this when most or all of your site or app should be server-rendered on request. Any individual page or endpoint can *opt-in* to pre-rendering. +- __`output: 'hybrid'`__: Pre-rendered to HTML by default. Use this when most of your site should be static. Any individual page or endpoint can *opt-out* of pre-rendering. + +Because the server will need to generate at least some pages on demand, both of these modes require you to [add an adapter](#add-an-adapter) to carry out the server functions. - export default defineConfig({ - output: 'server', - adapter: nodejs(), - }); - ``` +### Configure `server` or `hybrid` -- __`output: 'hybrid'`__: Pre-rendered to HTML by default. Use this when most of your site should be static. Any individual page or endpoint can *opt-out* of pre-rendering. +To enable on-demand rendering, first update your `output` configuration to one of the two server-rendered modes. + +For example, to configure a highly dynamic app where every page is rendered on demand by default, add `output: 'server'` to your Astro config: + +```js ins={5} title="astro.config.mjs" +import { defineConfig } from 'astro/config'; +import nodejs from '@astrojs/nodejs'; + +export default defineConfig({ + output: 'server', +}); +``` + +You can then choose to override the default on-demand rendering of `server` mode on any page or route by exporting `const prerender = true`: +```astro title="src/pages/my-static-page.astro" ins={2} +--- +export const prerender = true; +// ... +--- + + + +``` -You can then opt-out of the default rendering behavior with an export statement in any page or route: +### Opting-in to pre-rendering in `server` mode + +For a mostly server-rendered app configured as `output: server`, add `export const prerender = true` to any page or route to pre-render a static page or endpoint: ```astro title="src/pages/mypage.astro" {2} --- @@ -51,33 +71,53 @@ export const prerender = true; ``` -See more usage examples of [configuring individual routes](#configuring-individual-routes) -### Converting a static site to hybrid rendering +```mdx title="src/pages/mypage.mdx" {5} +--- +layout: '../layouts/markdown.astro' +title: 'My page' +--- +export const prerender = true; -To convert an existing static Astro site to allow hybrid rendering, change the `output` to `'hybrid'` and add an adapter: +# This is my static, pre-rendered page +``` -```js ins={2,5-8} title="astro.config.mjs" -import { defineConfig } from 'astro/config'; -import nodejs from '@astrojs/node'; +```js title="src/pages/myendpoint.js" {1} +export const prerender = true; -export default defineConfig({ - adapter: nodejs({ - mode: 'middleware' // or 'standalone' - }), - output: 'hybrid', -}); +export async function GET() { + return { + body: JSON.stringify({ message: `This is my static endpoint` }), + }; +} +``` + +### Opting out of pre-rendering in `hybrid` mode + +For a mostly static site configured as `output: hybrid`, add `export const prerender = false` to any files that should be server-rendered on demand: + +```js title="src/pages/randomnumber.js" {1} +export const prerender = false; + +export async function GET() { + let number = Math.random(); + return { + body: JSON.stringify({ number, message: `Here's a random number: ${number}` }), + }; +} ``` -### Adding an Adapter +### Add an Adapter + +To deploy a project in `server` or `hybrid` mode, you also need to add an **adapter**. This is because both of these modes require a server _runtime_: the environment that runs code on the server to generate pages when they are requested. Each adapter allows Astro to output a script that runs your project on a specific runtime, such as Vercel, Netlify or Cloudflare. -When it's time to deploy an SSR project, you also need to add an adapter. This is because SSR requires a server _runtime_: the environment that runs your server-side code. Each adapter allows Astro to output a script that runs your project on a specific runtime. +You can find both [official and community adapters in our integrations directory](https://astro.build/integrations/?search=&categories%5B%5D=adapters). Choose the one that corresponds to your [deployment environment](/en/guides/deploy/). -You can find both [official and community SSR adapters in our integrations directory](https://astro.build/integrations/?search=&categories%5B%5D=adapters). +#### `astro add` install -#### `astro add` Install +You can add any of the [official adapters maintained by Astro](/en/guides/integrations-guide/#official-integrations) with the following `astro add` command. This will install the adapter and make the appropriate changes to your `astro.config.mjs` file in one step. -You can add any of the [official Astro adapter integrations](/en/guides/integrations-guide/) with the following `astro add` command. This will install the adapter and make the appropriate changes to your `astro.config.mjs` file in one step. For example, to install the Vercel adapter, run: +For example, to install the Vercel adapter, run: @@ -99,137 +139,63 @@ You can add any of the [official Astro adapter integrations](/en/guides/integrat #### Manual Install -You can also add an adapter manually by installing the package and updating `astro.config.mjs` yourself. (See the links above for adapter-specific instructions to complete the following two steps to enable SSR.) Using `my-adapter` as an example placeholder, the instructions will look something like: +You can also add an adapter manually by installing the package and updating `astro.config.mjs` yourself. + +For example, to install the Vercel adapter manually: 1. Install the adapter to your project dependencies using your preferred package manager: ```shell - npm install @astrojs/my-adapter + npm install @astrojs/vercel ``` ```shell - pnpm install @astrojs/my-adapter + pnpm install @astrojs/vercel ``` ```shell - yarn add @astrojs/my-adapter + yarn add @astrojs/vercel ``` -2. [Add the adapter](/en/reference/configuration-reference/#adapter) to your `astro.config.mjs` file's import and default export: +2. [Add the adapter](/en/reference/configuration-reference/#adapter) to your `astro.config.mjs` file's import and default export, along with your desired `output` mode: - ```js ins={3,6-7} + ```js ins={3,7} {6} // astro.config.mjs import { defineConfig } from 'astro/config'; - import myAdapter from '@astrojs/my-adapter'; + import vercel from '@astrojs/vercel'; export default defineConfig({ output: 'server', - adapter: myAdapter(), + adapter: vercel(), }); ``` -## Features - -Astro will remain a static-site generator by default. But once you enable server-side rendering and add an adapter, a few new features become available to you. - -### Configuring individual routes + Note that different adapters may also have different configuration settings. Read each adapter's documentation, and apply any necessary config options to your chosen adapter in `astro.config.mjs` -Both `server` and `hybrid` modes allow for server-rendered pages and endpoints and will render all pages according to their default behavior. However, both modes allow you to mark an individual page to opt-out of this default behavior. +## On-demand rendering features -### Opting-out of server-rendering - -For a mostly server-rendered app configured as `output: server`, add `export const prerender = true` to any page or route to pre-render a static page or endpoint: +### HTML streaming -```astro title="src/pages/mypage.astro" {2} ---- -export const prerender = true; -// ... ---- - - - -``` - -```mdx title="src/pages/mypage.mdx" {5} ---- -layout: '../layouts/markdown.astro' -title: 'My page' ---- -export const prerender = true; - -# This is my static, pre-rendered page -``` +With HTML streaming, a document is broken up into chunks, sent over the network in order, and rendered on the page in that order. In `server` or `hybrid` mode, Astro uses HTML streaming to send each component to the browser as it renders them. This makes sure the user sees your HTML as fast as possible, although network conditions can cause large documents to be downloaded slowly, and waiting for data fetches can block page rendering. -And for an endpoint: - -```js title="src/pages/myendpoint.js" {1} -export const prerender = true; - -export async function GET() { - return { - body: JSON.stringify({ message: `This is my static endpoint` }), - }; -} -``` - -### Opting out of pre-rendering - -For a mostly static site configured as `output: hybrid`, add `export const prerender = false` to any files that should be server-rendered: - -```js title="src/pages/randomnumber.js" {1} -export const prerender = false; - -export async function GET() { - let number = Math.random(); - return { - body: JSON.stringify({ number, message: `Here's a random number: ${number}` }), - }; -} -``` - -### `Astro.request.headers` - -The headers for the request are available on `Astro.request.headers`. This works like the browser's [`Request.headers`](https://developer.mozilla.org/en-US/docs/Web/API/Request/headers). It is a [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object, a Map-like object where you can retrieve headers such as the cookie. - -```astro title="src/pages/index.astro" {2} ---- -const cookie = Astro.request.headers.get('cookie'); -// ... ---- - - - -``` - -### `Astro.request.method` - -The HTTP method used in the request is available as `Astro.request.method`. This works like the browser's [`Request.method`](https://developer.mozilla.org/en-US/docs/Web/API/Request/method). It returns the string representation of the HTTP method used in the request. - -```astro title="src/pages/index.astro" ---- -console.log(Astro.request.method) // GET (when navigated to in the browser) ---- -``` + :::caution -The features below are only available at the page level. (You can't use them inside of components, including layout components.) +Features that modify the [Response headers](https://developer.mozilla.org/en-US/docs/Glossary/Response_header) are only available at the **page level**. (You can't use them inside of components, including layout components.) By the time Astro runs your component code, it has already sent the Response headers and they cannot be modified. -This is because these features modify the [Response headers](https://developer.mozilla.org/en-US/docs/Glossary/Response_header), which can't be modified after they're sent to the browser. In SSR mode, Astro uses HTML streaming to send each component to the browser as it renders them. This makes sure the user sees your HTML as fast as possible, but it also means that by the time Astro runs your component code, it has already sent the Response headers. ::: -### `Astro.cookies` +### Cookies -This is a utility to read and modify a single cookie. It allows you to check, set, get and delete a cookie. +In `server` and `hybrid` modes, a page or API endpoint can check, set, get, and delete cookies. -See more details about [`Astro.cookies` and the `AstroCookie` type](/en/reference/api-reference/#astrocookies) in the API reference. - -The example below updates the value of a cookie for a page view counter. +The example below updates the value of a cookie for a page view counter: ```astro title="src/pages/index.astro" {4,5,9} --- @@ -240,16 +206,20 @@ if (Astro.cookies.has("counter")) { counter = cookie.number() + 1 } -Astro.cookies.set("counter", counter) +Astro.cookies.set("counter",counter) ---

Counter = {counter}

``` +See more details about [`Astro.cookies` and the `AstroCookie` type](/en/reference/api-reference/#astrocookies) in the API reference. + ### `Response` -You can also return a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) from any page. You might do this to return a 404 on a dynamic page after looking up an id in the database. +You can also return a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) from any page using on-demand rendering. + +The example below returns a 404 on a dynamic page after looking up an id in the database: ```astro title="src/pages/[id].astro" {8-11} --- @@ -270,108 +240,44 @@ if (!product) { ``` -### Server Endpoints - -A server endpoint, also known as an **API route**, is a special function exported from a `.js` or `.ts` file within the `src/pages/` folder. -The function takes an [endpoint context](/en/reference/api-reference/#endpoint-context) and returns a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). A powerful feature of SSR, API routes are able to securely execute code on the server. To learn more, see our [Endpoints Guide](/en/core-concepts/endpoints/#server-endpoints-api-routes). - -### Streaming +### `Request` -Browsers natively support HTTP streaming, where a document is broken up into chunks, sent over the network in order, and rendered on the page in that order. +`Astro.request` is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. It can be used to get the `url`, `headers`, `method`, and even body of the request. -During this process, browsers consume HTML incrementally: parsing, rendering into the DOM, and painting. This happens whether or not you intentionally stream your HTML. Network conditions can cause large documents to be downloaded slowly, and waiting for data fetches can block page rendering. +In both `server` and `hybrid` mode, you can access additional information from this object for pages that are not statically-generated. +#### `Astro.request.headers` -### Using streaming to improve page performance +The headers for the request are available on `Astro.request.headers`. This works like the browser's [`Request.headers`](https://developer.mozilla.org/en-US/docs/Web/API/Request/headers). It is a [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object where you can retrieve headers such as the cookie. -The following page `await`s some data in its frontmatter. Astro will wait for all of the `fetch` calls to resolve before sending any HTML to the browser. - -```astro title="src/pages/index.astro" +```astro title="src/pages/index.astro" {2} --- -const personResponse = await fetch('https://randomuser.me/api/'); -const personData = await personResponse.json(); -const randomPerson = personData.results[0]; -const factResponse = await fetch('https://catfact.ninja/fact'); -const factData = await factResponse.json(); +const cookie = Astro.request.headers.get('cookie'); +// ... --- - - A name and a fact - - -

A name

-

{randomPerson.name.first}

-

A fact

-

{factData.fact}

- + ``` -Moving the `await` calls into smaller components allows you to take advantage of Astro's streaming. Using the following components to perform the data fetches, Astro can render some HTML first, such as the title, and then the paragraphs when the data is ready. +#### `Astro.request.method` -```astro title="src/components/RandomName.astro" ---- -const personResponse = await fetch('https://randomuser.me/api/'); -const personData = await personResponse.json(); -const randomPerson = personData.results[0]; ---- -

{randomPerson.name.first}

-``` +The HTTP method used in the request is available as `Astro.request.method`. This works like the browser's [`Request.method`](https://developer.mozilla.org/en-US/docs/Web/API/Request/method). It returns the string representation of the HTTP method used in the request. -```astro title="src/components/RandomFact.astro" +```astro title="src/pages/index.astro" --- -const factResponse = await fetch('https://catfact.ninja/fact'); -const factData = await factResponse.json(); +console.log(Astro.request.method) // GET (when navigated to in the browser) --- -

{factData.fact}

``` +See more details about [`Astro.request`](/en/reference/api-reference/#astrorequest) in the API reference. -The Astro page below using these components can render parts of the page sooner. The ``, ``, and `

` tags are no longer blocked by data fetches. The server will then fetch data for `RandomName` and `RandomFact` in parallel and stream the resulting HTML to the browser. +### Server Endpoints -```astro title="src/pages/index.astro" ---- -import RandomName from '../components/RandomName.astro' -import RandomFact from '../components/RandomFact.astro' ---- - - - A name and a fact - - -

A name

- -

A fact

- - - -``` +A server endpoint, also known as an **API route**, is a special function exported from a `.js` or `.ts` file within the `src/pages/` folder. A powerful feature of server-side rendering on demand, API routes are able to securely execute code on the server. -#### Including Promises directly +The function takes an [endpoint context](/en/reference/api-reference/#endpoint-context) and returns a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). -You can also include promises directly in the template. Instead of blocking the entire component, it will resolve the promise in parallel and only block the markup that comes after it. +To learn more, see our [Endpoints Guide](/en/core-concepts/endpoints/#server-endpoints-api-routes). -```astro title="src/pages/index.astro" ---- -const personPromise = fetch('https://randomuser.me/api/') - .then(response => response.json()) - .then(arr => arr[0].name.first); -const factPromise = fetch('https://catfact.ninja/fact') - .then(response => response.json()) - .then(factData => factData.fact); ---- - - - A name and a fact - - -

A name

-

{personPromise}

-

A fact

-

{factPromise}

- - -``` -In this example, `A name` will render while `personPromise` and `factPromise` are loading. -Once `personPromise` has resolved, `A fact` will appear and `factPromise` will render when it's finished loading. diff --git a/src/content/docs/en/guides/typescript.mdx b/src/content/docs/en/guides/typescript.mdx index 53cb61fd8278e..b7cd5e8695551 100644 --- a/src/content/docs/en/guides/typescript.mdx +++ b/src/content/docs/en/guides/typescript.mdx @@ -44,7 +44,7 @@ If you are not using VSCode, you can install the [Astro TypeScript plugin](https
```shell - pnpm install @astrojs/ts-plugin + pnpm add @astrojs/ts-plugin ``` diff --git a/src/content/docs/en/guides/upgrade-to/v2.mdx b/src/content/docs/en/guides/upgrade-to/v2.mdx index 17faa6bc3d14a..f639574c24147 100644 --- a/src/content/docs/en/guides/upgrade-to/v2.mdx +++ b/src/content/docs/en/guides/upgrade-to/v2.mdx @@ -28,10 +28,10 @@ Update your project's version of Astro to the latest version using your package ```shell # Upgrade to Astro v2.x - pnpm install astro@latest + pnpm add astro@latest # Example: upgrade React and Tailwind integrations - pnpm install @astrojs/react@latest @astrojs/tailwind@latest + pnpm add @astrojs/react@latest @astrojs/tailwind@latest ``` @@ -415,7 +415,7 @@ export default defineConfig({ These features are now available by default: - [Content collections](/en/guides/content-collections/) as a way to manage your Markdown and MDX files with type-safety. -- [Prerendering individual pages to static HTML](/en/guides/server-side-rendering/#configuring-individual-routes) when using SSR to improve speed and cacheability. +- [Prerendering individual pages to static HTML](/en/guides/server-side-rendering/) when using SSR to improve speed and cacheability. - A redesigned error message overlay. ## Known Issues diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 1daa1566a3a43..f292b8543007c 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -28,10 +28,10 @@ Update your project's version of Astro to the latest version using your package ```shell # Upgrade to Astro v3.x - pnpm install astro@latest + pnpm add astro@latest # Example: upgrade React and Tailwind integrations - pnpm install @astrojs/react@latest @astrojs/tailwind@latest + pnpm add @astrojs/react@latest @astrojs/tailwind@latest ``` @@ -529,7 +529,7 @@ Astro v3.0 now includes Sharp as the default image processing service and instea When using a [strict package manager](https://pnpm.io/pnpm-vs-npm#npms-flat-tree) like `pnpm`, you may need to manually install Sharp into your project even though it is an Astro dependency: ```bash -pnpm install sharp +pnpm add sharp ``` ::: diff --git a/src/content/docs/en/guides/view-transitions.mdx b/src/content/docs/en/guides/view-transitions.mdx index 9646e0d72fcca..975f998ba2ebd 100644 --- a/src/content/docs/en/guides/view-transitions.mdx +++ b/src/content/docs/en/guides/view-transitions.mdx @@ -252,7 +252,7 @@ The following options allow you to further control when navigation occurs within There are some cases where you cannot navigate via client-side routing since both pages involved must use the `` router to prevent a full-page reload. You may also not want client-side routing on every navigation change and would prefer a traditional page navigation on select routes instead. -You can opt out of client-side routing on a per-link basis by adding the `data-astro-reload` attribute to any `
` tag. This attribute will override any existing `` component and instead trigger a browser refresh during navigation. +You can opt out of client-side routing on a per-link basis by adding the `data-astro-reload` attribute to any `` or `
` tag. This attribute will override any existing `` component and instead trigger a browser refresh during navigation. The following example shows preventing client-side routing when navigating to an article from the home page only. This still allows you to have animation on shared elements, such as a hero image, when navigating to the same page from an article listing page: @@ -343,6 +343,7 @@ The `navigate` method takes these arguments: - `'push'`: the router will use `history.pushState` to create a new entry in the browser history. - `'replace'`: the router will use `history.replaceState` to update the URL without adding a new entry into navigation. - `'auto'` (default): the router will attempt `history.pushState`, but if the URL is not one that can be transitioned to, the current URL will remain with no changes to the browser history. + - `formData`: A FormData object for `POST` requests. For backward and forward navigation through the browser history, you can combine `navigate()` with the built-in `history.back()`, `history.forward()` and `history.go()` functions of the browser. If `navigate()` is called during the server-side render of your component, it has no effect. @@ -367,6 +368,33 @@ The following example navigates to the `/main` page but does not add a new entry This has the effect that if you go back from the `/main` page, the browser will not display the `/confirmation` page, but the page before it. +### Transitions with forms + + + +By default, the `` router only transitions on navigation triggered by `` clicks. You can also allow transitions on form submissions by adding the `handleForms` option on the router. + +```astro title="src/pages/index.astro" +--- +import { ViewTransitions } from "astro:transitions"; +--- + + + + + + + + +``` + +With this option the router will trigger in-page transitions from `` elements, supporting both `GET` and `POST` requests. You can opt out of router transitions on any individual form using the `data-astro-reload` attribute: + +```astro title="src/components/Form.astro" + + + +``` ## Fallback control @@ -552,7 +580,7 @@ import { ViewTransitions } from "astro:components astro:transitions" **Changed:** The `transition:animate` value `morph` has been renamed to `initial`. Also, this is no longer the default animation. If no `transition:animate` directive is specified, your animations will now default to `fade`. -1. Rename any `morph` animations to `intial`. +1. Rename any `morph` animations to `initial`. ```astro title="src/components/MyComponent.astro" del="morph" ins="initial"
``` diff --git a/src/content/docs/en/install/manual.mdx b/src/content/docs/en/install/manual.mdx index af3b88279a5aa..188bdc2a6bd17 100644 --- a/src/content/docs/en/install/manual.mdx +++ b/src/content/docs/en/install/manual.mdx @@ -71,7 +71,7 @@ Astro must be installed locally, not globally. Make sure you are *not* running ` ```shell - pnpm install astro + pnpm install astro ``` diff --git a/src/content/docs/en/recipes.mdx b/src/content/docs/en/recipes.mdx index 2dc8aabdd82dc..fbf768c1a7ef1 100644 --- a/src/content/docs/en/recipes.mdx +++ b/src/content/docs/en/recipes.mdx @@ -38,3 +38,4 @@ Add your own here! See our [recipes contributing guide](https://github.com/witha - [Add Github OAuth with Lucia](https://lucia-auth.com/guidebook/github-oauth/astro) - [Integrating Sentry with Astro](https://akashrajpurohit.com/blog/seamless-error-tracking-integrating-sentry-with-astro/) - [Set Up Draft Pages Effectively in Astro with Config-Driven Content Authoring](https://akashrajpurohit.com/blog/set-up-draft-pages-effectively-in-astro-with-configdriven-content-authoring/) +- [How to Send Any Data to Your RSS Feed? A Guide with Astro + RSS](https://aritraroy.live/tutorial/blogs/2023/how-to-send-any-data-to-rss-feed/) diff --git a/src/content/docs/en/recipes/build-custom-img-component.mdx b/src/content/docs/en/recipes/build-custom-img-component.mdx new file mode 100644 index 0000000000000..6346f345411ba --- /dev/null +++ b/src/content/docs/en/recipes/build-custom-img-component.mdx @@ -0,0 +1,128 @@ +--- +title: Build a custom image component +description: Learn how to build a custom image component that supports media queries using the getImage function +i18nReady: true +type: recipe +--- + +Astro provides two built-in components that you can use to display and optimize your images. The `` component allows you to display responsive images and work with different formats and sizes. The `` component will optimize your images and allow you to pass in different formats and quality properties. + +When you need options that the `` and `` components do not currently support, you can use the `getImage()` function to create a custom component. + +In this recipe, you will use the [`getImage()` function](/en/guides/images/#generating-images-with-getimage) to create your own custom image component that displays different source images based on media queries. + +## Recipe + +1. Create a new Astro component and import the `getImage()` function + + ```astro title="src/components/MyCustomImageComponent.astro" + --- + import { getImage } from "astro:assets"; + --- + + ``` + +2. Create a new component for your custom image. `MyCustomComponent.astro` will receive three `props` from `Astro.props`. The `mobileImgUrl` and `desktopImgUrl` props are used for creating your image at different viewport sizes. The `alt` prop is used for the image's alt text. These props will be passed wherever you render your custom image components. Add the following imports and define the props that you will use in your component. You can also use TypeScript to type the props. + + ```astro title="src/components/MyCustomImageComponent.astro" ins={3, 11} + --- + import type { ImageMetadata } from "astro"; + import { getImage } from "astro:assets"; + + interface Props { + mobileImgUrl: string | ImageMetadata; + desktopImgUrl: string | ImageMetadata; + alt: string; + } + + const { mobileImgUrl, desktopImgUrl, alt } = Astro.props; + --- + + ``` + +3. Define each of your responsive images by calling the `getImage()` function with your desired properties. + + ```astro title="src/components/MyCustomImageComponent.astro" ins={13-18, 20-25} + --- + import type { ImageMetadata } from "astro"; + import { getImage } from "astro:assets"; + + interface Props { + mobileImgUrl: string | ImageMetadata; + desktopImgUrl: string | ImageMetadata; + alt: string; + } + + const { mobileImgUrl, desktopImgUrl, alt } = Astro.props; + + const mobileImg = await getImage({ + src: mobileImgUrl, + format: "webp", + width: 200, + height: 200, + }); + + const desktopImg = await getImage({ + src: desktopImgUrl, + format: "webp", + width: 800, + height: 200, + }); + --- + + ``` + +4. Create a `` element that generates a `srcset` with your different images based on your desired media queries. + + ```astro title="src/components/MyCustomImageComponent.astro" ins={28-32} + --- + import type { ImageMetadata } from "astro"; + import { getImage } from "astro:assets"; + + interface Props { + mobileImgUrl: string | ImageMetadata; + desktopImgUrl: string | ImageMetadata; + alt: string; + } + + const { mobileImgUrl, desktopImgUrl, alt } = Astro.props; + + const mobileImg = await getImage({ + src: mobileImgUrl, + format: "webp", + width: 200, + height: 200, + }); + + const desktopImg = await getImage({ + src: desktopImgUrl, + format: "webp", + width: 800, + height: 200, + }); + --- + + + + + {alt} + + + ``` + +5. Import and use `` in any `.astro` file. Be sure to pass the necessary props for generating two different images at the different viewport sizes: + + ```astro title="src/pages/index.astro" + --- + import MyCustomImageComponent from "../components/MyCustomImageComponent.astro"; + import mobileImage from "../images/mobile-profile-image.jpg"; + import desktopImage from "../images/desktop-profile-image.jpg"; + --- + + + + ``` diff --git a/src/content/docs/en/recipes/modified-time.mdx b/src/content/docs/en/recipes/modified-time.mdx index 00e825d539a97..503362eab28e4 100644 --- a/src/content/docs/en/recipes/modified-time.mdx +++ b/src/content/docs/en/recipes/modified-time.mdx @@ -23,7 +23,7 @@ Learn how to build a [remark plugin](https://github.com/remarkjs/remark) that ad ```shell - pnpm install dayjs + pnpm add dayjs ``` diff --git a/src/content/docs/en/recipes/reading-time.mdx b/src/content/docs/en/recipes/reading-time.mdx index c7ce136f24eaa..21be996d3989a 100644 --- a/src/content/docs/en/recipes/reading-time.mdx +++ b/src/content/docs/en/recipes/reading-time.mdx @@ -25,7 +25,7 @@ Create a [remark plugin](https://github.com/remarkjs/remark) which adds a readin ```shell - pnpm install reading-time mdast-util-to-string + pnpm add reading-time mdast-util-to-string ``` diff --git a/src/content/docs/en/recipes/sharing-state.mdx b/src/content/docs/en/recipes/sharing-state.mdx index e4e8f61e3eab7..114eff86b50a7 100644 --- a/src/content/docs/en/recipes/sharing-state.mdx +++ b/src/content/docs/en/recipes/sharing-state.mdx @@ -25,7 +25,7 @@ When building an Astro website, you may need to share state across components. A ```shell - pnpm install nanostores + pnpm add nanostores ``` diff --git a/src/content/docs/en/recipes/streaming-improve-page-performance.mdx b/src/content/docs/en/recipes/streaming-improve-page-performance.mdx new file mode 100644 index 0000000000000..a14be8dee5131 --- /dev/null +++ b/src/content/docs/en/recipes/streaming-improve-page-performance.mdx @@ -0,0 +1,102 @@ +--- +title: "Using streaming to improve page performance" +description: "Learn how to use streaming to improve page performance." +type: recipe +i18nReady: true +--- + +Astro's SSR uses HTML streaming to send each component to the browser when available for faster page loading. To improve your page's performance even further, you can build your components strategically to optimize their loading by avoiding blocking data fetches. + +The following refactoring example demonstrates how to improve page performance by moving fetch calls to other components, moving them out of a component where they block page rendering. + +The following page `await`s some data in its frontmatter. Astro will wait for all of the `fetch` calls to resolve before sending any HTML to the browser. + +```astro title="src/pages/index.astro" +--- +const personResponse = await fetch('https://randomuser.me/api/'); +const personData = await personResponse.json(); +const randomPerson = personData.results[0]; +const factResponse = await fetch('https://catfact.ninja/fact'); +const factData = await factResponse.json(); +--- + + + A name and a fact + + +

A name

+

{randomPerson.name.first}

+

A fact

+

{factData.fact}

+ + +``` + +Moving the `await` calls into smaller components allows you to take advantage of Astro's streaming. Using the following components to perform the data fetches, Astro can render some HTML first, such as the title, and then the paragraphs when the data is ready. + +```astro title="src/components/RandomName.astro" +--- +const personResponse = await fetch('https://randomuser.me/api/'); +const personData = await personResponse.json(); +const randomPerson = personData.results[0]; +--- +

{randomPerson.name.first}

+``` + +```astro title="src/components/RandomFact.astro" +--- +const factResponse = await fetch('https://catfact.ninja/fact'); +const factData = await factResponse.json(); +--- +

{factData.fact}

+``` + + +The Astro page below using these components can render parts of the page sooner. The ``, ``, and `

` tags are no longer blocked by data fetches. The server will then fetch data for `RandomName` and `RandomFact` in parallel and stream the resulting HTML to the browser. + +```astro title="src/pages/index.astro" +--- +import RandomName from '../components/RandomName.astro' +import RandomFact from '../components/RandomFact.astro' +--- + + + A name and a fact + + +

A name

+ +

A fact

+ + + +``` + +#### Including Promises directly + +You can also include promises directly in the template. Instead of blocking the entire component, it will resolve the promise in parallel and only block the markup that comes after it. + +```astro title="src/pages/index.astro" +--- +const personPromise = fetch('https://randomuser.me/api/') + .then(response => response.json()) + .then(arr => arr[0].name.first); +const factPromise = fetch('https://catfact.ninja/fact') + .then(response => response.json()) + .then(factData => factData.fact); +--- + + + A name and a fact + + +

A name

+

{personPromise}

+

A fact

+

{factPromise}

+ + +``` + +In this example, `A name` will render while `personPromise` and `factPromise` are loading. +Once `personPromise` has resolved, `A fact` will appear and `factPromise` will render when it's finished loading. \ No newline at end of file diff --git a/src/content/docs/en/recipes/tailwind-rendered-markdown.mdx b/src/content/docs/en/recipes/tailwind-rendered-markdown.mdx new file mode 100644 index 0000000000000..9dedaa47b5622 --- /dev/null +++ b/src/content/docs/en/recipes/tailwind-rendered-markdown.mdx @@ -0,0 +1,107 @@ +--- +title: Style Rendered Markdown with Tailwind Typography +description: Learn how to use @tailwind/typography to style your rendered Markdown +i18nReady: true +type: recipe +--- + +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; + +You can use [Tailwind](https://tailwindcss.com)'s Typography plugin to style rendered Markdown from sources such as Astro's [**content collections**](/en/guides/content-collections/). + +This recipe will teach you how to create a reusable Astro component to style your Markdown content using Tailwind's utility classes. + +## Prerequisites + +An Astro project that: + + - has [Astro's Tailwind integration](/en/guides/integrations-guide/tailwind/) installed. + - uses Astro's [content collections](/en/guides/content-collections/). + +## Setting Up `@tailwindcss/typography` + +First, install `@tailwindcss/typography` using your preferred package manager. + + + + ```shell + npm install -D @tailwindcss/typography + ``` + + + ```shell + pnpm add -D @tailwindcss/typography + ``` + + + ```shell + yarn add --dev @tailwindcss/typography + ``` + + + +Then, add the package as a plugin in your Tailwind configuration file. + +```diff lang="js" +// tailwind.config.js +/** @type {import('tailwindcss').Config} */ + +export default { + theme: { + // ... + }, + plugins: [ ++ require('@tailwindcss/typography'), + // ... + ], +} +``` + +## Recipe + +1. Create a ` ` component to provide a wrapping `
` with a `` for your rendered Markdown. Add the style class `prose` alongside any desired [Tailwind element modifiers](https://tailwindcss.com/docs/typography-plugin#element-modifiers) in the parent element. + + ```astro title="src/components/Prose.astro" + --- + --- +
+ +
+ ``` + :::tip + The `@tailwindcss/typography` plugin uses [**element modifiers**](https://tailwindcss.com/docs/typography-plugin#element-modifiers) to style child components of a container with the `prose` class. + + These modifiers follow the following general syntax: + + ``` + prose-[element]:class-to-apply + ``` + + For example, `prose-h1:font-bold` gives all `

` tags the `font-bold` Tailwind class. + ::: + +2. Query your collection entry on the page you want to render your Markdown. Pass the `` component from `await entry.render()` to `` as a child to wrap your Markdown content in Tailwind styles. + + ```astro title="src/pages/index.astro" + --- + import Prose from "../components/Prose.astro"; + import Layout from "../layouts/Layout.astro"; + import { getEntry } from 'astro:content'; + + const entry = await getEntry('collection', 'entry'); + const { Content } = await entry.render(); + --- + + + + + + ``` + +## Resources + +- [Tailwind Typography Documentation](https://tailwindcss.com/docs/typography-plugin) diff --git a/src/content/docs/en/reference/adapter-reference.mdx b/src/content/docs/en/reference/adapter-reference.mdx index 68710b6a30047..957f300f4a97e 100644 --- a/src/content/docs/en/reference/adapter-reference.mdx +++ b/src/content/docs/en/reference/adapter-reference.mdx @@ -6,7 +6,7 @@ import Since from '~/components/Since.astro'; import FileTree from '~/components/FileTree.astro'; -Astro is designed to make it easy to deploy to any cloud provider for SSR (server-side rendering). This ability is provided by __adapters__, which are [integrations](/en/reference/integrations-reference/). See the [SSR guide](/en/guides/server-side-rendering/#adding-an-adapter) to learn how to use an existing adapter. +Astro is designed to make it easy to deploy to any cloud provider for SSR (server-side rendering). This ability is provided by __adapters__, which are [integrations](/en/reference/integrations-reference/). See the [SSR guide](/en/guides/server-side-rendering/) to learn how to use an existing adapter. ## What is an adapter diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index 68e6c61ea37a5..2f759ed74e645 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -4,7 +4,7 @@ i18nReady: true --- import Since from '~/components/Since.astro' import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - +import Badge from '~/components/Badge.astro'; ## `Astro` global @@ -779,7 +779,56 @@ Pagination will pass a `page` prop to every rendered page that represents a sing | `page.url.prev` | `string \| undefined` | Get the URL of the previous page (will be `undefined` if on page 1). | | `page.url.next` | `string \| undefined` | Get the URL of the next page (will be `undefined` if no more pages). | -## Content Collections + + + + +## `import.meta` + +All ESM modules include a `import.meta` property. Astro adds `import.meta.env` through [Vite](https://vitejs.dev/guide/env-and-mode.html). + +**`import.meta.env.SSR`** can be used to know when rendering on the server. Sometimes you might want different logic, like a component that should only be rendered in the client: + +```jsx +export default function () { + return import.meta.env.SSR ?
: ; +} +``` + +## Images (`astro:assets`) + +### getImage() + +:::caution +`getImage()` relies on server-only APIs and breaks the build when used on the client. +::: + +The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/core-concepts/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `` component. + +`getImage()` takes an options object with the [same properties as the Image component](#properties) (except `alt`). + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +It returns an object with the following properties: + +```js +{ + options: {...} // Original parameters passed + src: "https//..." // Path to the generated image + attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..) +} +``` + +## Content Collections (`astro:content`)

@@ -1084,18 +1133,6 @@ const blog = defineCollection({ }); ``` -## `import.meta` - -All ESM modules include a `import.meta` property. Astro adds `import.meta.env` through [Vite](https://vitejs.dev/guide/env-and-mode.html). - -**`import.meta.env.SSR`** can be used to know when rendering on the server. Sometimes you might want different logic, for example a component that should only be rendered in the client: - -```jsx -export default function () { - return import.meta.env.SSR ?

: ; -} -``` - ## Built-in Components Astro includes several built-in components for you to use in your projects. All built-in components are available in `.astro` files via `import {} from 'astro:components';`. @@ -1121,6 +1158,19 @@ import { Code } from 'astro:components'; This component provides syntax highlighting for code blocks at build time (no client-side JavaScript included). The component is powered internally by Shiki and it supports all popular [themes](https://github.com/shikijs/shiki/blob/main/docs/themes.md) and [languages](https://github.com/shikijs/shiki/blob/main/docs/languages.md). Plus, you can add your custom themes and languages by passing them to `theme` and `lang` respectively. +### `` + +A component used with [`set:*` directives](/en/reference/directives-reference/#sethtml) to render HTML content without any additional wrapping elements: + +```astro title="src/components/SetHtml.astro" "Fragment" +--- +const htmlString = '

Raw HTML content

'; +--- + +``` + +See more about [using fragments](/en/core-concepts/astro-syntax/#fragments) in Astro syntax. + ### `` To use the `Prism` highlighter component, first **install** the `@astrojs/prism` package: @@ -1133,7 +1183,7 @@ To use the `Prism` highlighter component, first **install** the `@astrojs/prism` ```shell - pnpm install @astrojs/prism + pnpm add @astrojs/prism ``` @@ -1154,6 +1204,133 @@ This component provides language-specific syntax highlighting for code blocks by See the [list of languages supported by Prism](https://prismjs.com/#supported-languages) where you can find a language’s corresponding alias. And, you can also display your Astro code blocks with `lang="astro"`! +### `` + +```astro title="src/components/MyComponent.astro" +--- +// import the Image component and the image +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // Image is 1600x900 +--- + + +A description of my image. +``` + +```html + + +A description of my image. +``` +#### Properties + +- src (required) +- alt (required) +- width and height (required for `public/` and remote images) +- format +- quality +- densities +- widths + +In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. + +See more in the [Images Guide](/en/guides/images/#image--astroassets). + +### `` + + Experimental + +Use the built-in `` Astro component to display a responsive image with multiple formats and/or sizes. + +```astro title="src/pages/index.astro" +--- +import { Picture } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // Image is 1600x900 +--- + + + +``` + +```html + + + + + A description of my image. + +``` + +See more in the [Images Guide](/en/guides/images/#picture-). + +#### Properties + +`` accepts all the properties of the `` component, plus the following: + +##### `formats` + +An array of image formats to use for the `` tags. By default, this is set to `['webp']`. + +##### `fallbackFormat` + +Format to use as a fallback value for the `` tag. Defaults to `.png` for static images, `.gif` for animated images, and `.svg` for SVG files. + +##### `pictureAttributes` + +An object of attributes to be added to the `` tag. Use this property to apply attributes to the outer `` element itself. Attributes applied to the `` component directly will apply to the inner `` element, except for those used for image transformation. + + +### `` + +A generic component used to render the content of a [content collection entry](/en/guides/content-collections/#what-are-content-collections). + +First, query one or more entries using `getCollection()` or `getEntry()`. Then, the `entry.render()` function can return the `` component for use in a `.astro` file template. + +```astro title="src/pages/render-example.astro" {4, 7} +--- +import { getEntry } from 'astro:content'; +const entry = await getEntry('blog', 'post-1'); +const { Content } = await entry.render(); +--- +

Published on: {entry.data.published.toDateString()}

+ +``` + +### `` + +Opt in to using view transitions on individual pages by importing and adding the `` routing component to `` on every desired page. + +```astro title="src/pages/index.astro" ins={2,7} +--- +import { ViewTransitions } from 'astro:transitions'; +--- + + + My Homepage + + + +

Welcome to my website!

+ + +``` + +See more about how to [control the router](/en/guides/view-transitions/#router-control) and [add transition directives](/en/guides/view-transitions/#transition-directives) to page elements and components. + ### `` ```astro diff --git a/src/content/docs/en/reference/cli-reference.mdx b/src/content/docs/en/reference/cli-reference.mdx index 4f2ed3160b1ca..bd8190ea1b7b4 100644 --- a/src/content/docs/en/reference/cli-reference.mdx +++ b/src/content/docs/en/reference/cli-reference.mdx @@ -243,13 +243,9 @@ Use these flags to customize the behavior of the command. #### `--watch` -The command will watch for any changes to `.astro` files, and will report any errors. +The command will watch for any changes in your project, and will report any errors. -:::note -This command only checks types within `.astro` files. -::: - -📚 Read more about [TypeScript support in Astro](/en/guides/typescript/). +📚 Read more about [type checking in Astro](/en/guides/typescript/#type-checking). ## `astro sync` diff --git a/src/content/docs/en/reference/configuration-reference.mdx b/src/content/docs/en/reference/configuration-reference.mdx index 2d3b4c14328e4..9ff8e7543aebd 100644 --- a/src/content/docs/en/reference/configuration-reference.mdx +++ b/src/content/docs/en/reference/configuration-reference.mdx @@ -26,6 +26,7 @@ export default defineConfig({ ``` ## Top-Level Options + ### root

@@ -50,7 +51,6 @@ If you provide a relative path (ex: `--root: './my-project'`) Astro will resolve $ astro build --root ./my-project-directory ``` - ### srcDir

@@ -69,7 +69,6 @@ The value can be either an absolute file system path or a path relative to the p } ``` - ### publicDir

@@ -88,7 +87,6 @@ The value can be either an absolute file system path or a path relative to the p } ``` - ### outDir

@@ -109,7 +107,6 @@ The value can be either an absolute file system path or a path relative to the p **See Also:** - build.server - ### cacheDir

@@ -128,7 +125,6 @@ The value can be either an absolute file system path or a path relative to the p } ``` - ### redirects

@@ -175,7 +171,6 @@ You can customize the [redirection status code](https://developer.mozilla.org/en } ``` - ### site

@@ -191,7 +186,6 @@ Your final, deployed URL. Astro uses this full URL to generate your sitemap and } ``` - ### compressHTML

@@ -209,7 +203,6 @@ To disable HTML compression, set the `compressHTML` flag to `false`. } ``` - ### base

@@ -229,8 +222,28 @@ In the example below, `astro dev` will start your server at `/docs`. When using this option, all of your static asset imports and URLs should add the base as a prefix. You can access this value via `import.meta.env.BASE_URL`. -The value of `import.meta.env.BASE_URL` respects your `trailingSlash` config and will include a trailing slash if you explicitly include one or if `trailingSlash: "always"` is set. If `trailingSlash: "never"` is set, `BASE_URL` will not include a trailing slash, even if `base` includes one. +The value of `import.meta.env.BASE_URL` will be determined by your `trailingSlash` config, no matter what value you have set for `base`. + +A trailing slash is always included if `trailingSlash: "always"` is set. If `trailingSlash: "never"` is set, `BASE_URL` will not include a trailing slash, even if `base` includes one. +Additionally, Astro will internally manipulate the configured value of `config.base` before making it available to integrations. The value of `config.base` as read by integrations will also be determined by your `trailingSlash` configuration in the same way. + +In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs`: +```js +{ + base: '/docs/', + trailingSlash: "never" +} +``` + +In the example below, the values of `import.meta.env.BASE_URL` and `config.base` when processed will both be `/docs/`: + +```js +{ + base: '/docs', + trailingSlash: "always" +} +``` ### trailingSlash @@ -258,7 +271,6 @@ You can also set this if you prefer to be more strict yourself, so that URLs wit **See Also:** - build.format - ### scopedStyleStrategy

@@ -277,7 +289,6 @@ Using `'class'` is helpful when you want to ensure that element selectors within Using `'where'` gives you more control over specificity, but requires that you use higher-specificity selectors, layers, and other tools to control which selectors are applied. Using `'attribute'` is useful when you are manipulating the `class` attribute of elements and need to avoid conflicts between your own styling logic and Astro's application of styles. - ### adapter

@@ -299,7 +310,6 @@ import netlify from '@astrojs/netlify/functions'; **See Also:** - output - ### output

@@ -324,9 +334,9 @@ export default defineConfig({ **See Also:** - adapter - ## Build Options + ### build.format

@@ -359,7 +369,6 @@ To prevent inconsistencies with trailing slash behaviour in dev, you can restric - `directory` - Set `trailingSlash: 'always'` - `file` - Set `trailingSlash: 'never'` - ### build.client

@@ -382,7 +391,6 @@ This value is relative to the `outDir`. } ``` - ### build.server

@@ -403,7 +411,6 @@ This value is relative to the `outDir`. } ``` - ### build.assets

@@ -425,7 +432,6 @@ Specifies the directory in the build output where Astro-generated assets (bundle **See Also:** - outDir - ### build.assetsPrefix

@@ -450,7 +456,6 @@ To rename the `_astro` path, specify a new directory in `build.assets`. } ``` - ### build.serverEntry

@@ -474,7 +479,6 @@ detects that the file is a JavaScript module. } ``` - ### build.redirects

@@ -499,7 +503,6 @@ configuration files for redirects and do not need/want HTML based redirects. } ``` - ### build.inlineStylesheets

@@ -522,7 +525,6 @@ Control whether project styles are sent to the browser in a separate css file or } ``` - ### build.split @@ -540,7 +542,6 @@ The build config option `build.split` has been replaced by the adapter configura Please see your [SSR adapter's documentation](/en/guides/integrations-guide/#official-integrations) for using `functionPerRoute` to define how your SSR code is bundled. - ### build.excludeMiddleware @@ -558,6 +559,68 @@ The build config option `build.excludeMiddleware` has been replaced by the adapt Please see your [SSR adapter's documentation](/en/guides/integrations-guide/#official-integrations) for using `edgeMiddleware` to define whether or not any SSR middleware code will be bundled when built. +## Prefetch Options + +

+ +**Type:** `boolean | object` +

+ +Enable prefetching for links on your site to provide faster page transitions. +(Enabled by default on pages using the `` router. Set `prefetch: false` to opt out of this behaviour.) + +This configuration automatically adds a prefetch script to every page in the project +giving you access to the `data-astro-prefetch` attribute. +Add this attribute to any `
` link on your page to enable prefetching for that page. + +```html +About +``` +Further customize the default prefetching behavior using the [`prefetch.defaultStrategy`](#prefetchdefaultstrategy) and [`prefetch.prefetchAll`](#prefetchprefetchall) options. + +See the [Prefetch guide](/en/guides/prefetch/) for more information. + +### prefetch.prefetchAll + +

+ +**Type:** `boolean` +

+ +Enable prefetching for all links, including those without the `data-astro-prefetch` attribute. +This value defaults to `true` when using the `` router. Otherwise, the default value is `false`. + +```js +prefetch: { + prefetchAll: true +} +``` + +When set to `true`, you can disable prefetching individually by setting `data-astro-prefetch="false"` on any individual links. + +```html +About +``` + +### prefetch.defaultStrategy + +

+ +**Type:** `'tap' | 'hover' | 'viewport'`
+**Default:** `'hover'` +

+ +The default prefetch strategy to use when the `data-astro-prefetch` attribute is set on a link with no value. + +- `'tap'`: Prefetch just before you click on the link. +- `'hover'`: Prefetch when you hover over or focus on the link. (default) +- `'viewport'`: Prefetch as the links enter the viewport. + +You can override this default value and select a different strategy for any individual link by setting a value on the attribute. + +```html +About +``` ## Server Options @@ -592,7 +655,6 @@ Set which network IP addresses the server should listen on (i.e. non-localhost I - `true` - listen on all addresses, including LAN and public addresses - `[custom-address]` - expose on a network IP address at `[custom-address]` (ex: `192.168.0.1`) - ### server.port

@@ -611,7 +673,6 @@ If the given port is already in use, Astro will automatically try the next avail } ``` - ### server.headers

@@ -623,9 +684,9 @@ If the given port is already in use, Astro will automatically try the next avail Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. - ## Image Options + ### image.endpoint

@@ -648,7 +709,6 @@ The endpoint will always be injected at `/_image`. } ``` - ### image.service

@@ -673,7 +733,6 @@ The service entrypoint can be either one of the included services, or a third-pa } ``` - ### image.domains

@@ -697,7 +756,6 @@ This option requires an array of individual domain names as strings. Wildcards a } ``` - ### image.remotePatterns

@@ -736,9 +794,9 @@ You can use wildcards to define the permitted `hostname` and `pathname` values a - End with '/**' to allow all sub-routes ('startsWith'). - End with '/*' to allow only one level of sub-route. - ## Markdown Options + ### markdown.drafts @@ -765,7 +823,6 @@ A Markdown page is considered a draft if it includes `draft: true` in its frontm } ``` - ### markdown.shikiConfig

@@ -775,7 +832,6 @@ A Markdown page is considered a draft if it includes `draft: true` in its frontm Shiki configuration options. See [the Markdown configuration docs](/en/guides/markdown-content/#shiki-configuration) for usage. - ### markdown.syntaxHighlight

@@ -798,7 +854,6 @@ Which syntax highlighter to use, if any. } ``` - ### markdown.remarkPlugins

@@ -817,7 +872,6 @@ import remarkToc from 'remark-toc'; } ``` - ### markdown.rehypePlugins

@@ -836,7 +890,6 @@ import { rehypeAccessibleEmojis } from 'rehype-accessible-emojis'; } ``` - ### markdown.gfm

@@ -856,7 +909,6 @@ Astro uses [GitHub-flavored Markdown](https://github.com/remarkjs/remark-gfm) by } ``` - ### markdown.smartypants

@@ -876,7 +928,6 @@ Astro uses the [SmartyPants formatter](https://daringfireball.net/projects/smart } ``` - ### markdown.remarkRehype

@@ -895,7 +946,6 @@ Pass options to [remark-rehype](https://github.com/remarkjs/remark-rehype#api). }; ``` - ## Integrations Extend Astro with custom integrations. Integrations are your one-stop-shop for adding framework support (like Solid.js), new features (like sitemaps), and new libraries (like Partytown). @@ -972,4 +1022,126 @@ Enable hoisted script analysis optimization by adding the experimental flag: } ``` +### experimental.devOverlay + +

+ +**Type:** `boolean`
+**Default:** `false`
+ +

+ +Enable a dev overlay in development mode. This overlay allows you to inspect your page islands, see helpful audits on performance and accessibility, and more. + +```js +{ + experimental: { + devOverlay: true, + }, +} +``` + +### experimental.i18n + +

+ +**Type:** `object`
+ +

+ +Configures experimental i18n routing and allows you to specify some customization options. + +See our guide for more information on [internationalization in Astro](/en/guides/internationalization/) + +#### experimental.i18n.defaultLocale + +

+ +**Type:** `string`
+ +

+ +The default locale of your website/application. This is a required field. + +No particular language format or syntax is enforced, but we suggest using lower-case and hyphens as needed (e.g. "es", "pt-br") for greatest compatibility. + +#### experimental.i18n.locales + +

+ +**Type:** `Array.`
+ +

+ +A list of all locales supported by the website (e.g. `['en', 'es', 'pt-br']`). This list should also include the `defaultLocale`. This is a required field. + +No particular language format or syntax is enforced, but your folder structure must match exactly the locales in the list. + +#### experimental.i18n.fallback + +

+ +**Type:** `Record.`
+ +

+ +The fallback strategy when navigating to pages that do not exist (e.g. a translated page has not been created). + +Use this object to declare a fallback `locale` route for each language you support. If no fallback is specified, then unavailable pages will return a 404. + +##### Example + +The following example configures your content fallback strategy to redirect unavailable pages in `/pt-br/` to their `es` version, and unavailable pages in `/fr/` to their `en` version. Unavailable `/es/` pages will return a 404. + +```js +export defualt defineConfig({ + experimental: { + i18n: { + defaultLocale: "en", + locales: ["en", "fr", "pt-br", "es"], + fallback: { + pt: "es", + fr: "en" + } + } + } +}) +``` + +#### experimental.i18n.routingStrategy + +

+ +**Type:** `'prefix-always' | 'prefix-other-locales'`
+**Default:** 'prefix-other-locales'
+ +

+ +Controls the routing strategy to determine your site URLs. Set this based on your folder/URL path configuration for your default language: + + - `prefix-other-locales`(default): Only non-default languages will display a language prefix. + The `defaultLocale` will not show a language prefix and content files do not exist in a localized folder. + URLs will be of the form `example.com/[locale]/content/` for all non-default languages, but `example.com/content/` for the default locale. + - `prefix-always`: All URLs will display a language prefix. + URLs will be of the form `example.com/[locale]/content/` for every route, including the default language. + Localized folders are used for every language, including the default. + +### experimental.contentCollectionCache + +

+ +**Type:** `boolean`
+**Default:** `false`
+ +

+ +Enables a persistent cache for content collections when building in static mode. + +```js +{ + experimental: { + contentCollectionCache: true, + }, +} +``` diff --git a/src/content/docs/en/reference/dev-overlay-plugin-reference.mdx b/src/content/docs/en/reference/dev-overlay-plugin-reference.mdx new file mode 100644 index 0000000000000..87ba6b5f01375 --- /dev/null +++ b/src/content/docs/en/reference/dev-overlay-plugin-reference.mdx @@ -0,0 +1,356 @@ +--- +title: Dev Overlay Plugin API +i18nReady: false +--- + +The Astro Dev Overlay Plugin API allows you to create plugins that can be used to extend the Astro Dev Overlay. This allows you to add new features and integrations with third-party services. + +:::note +This API is currently **experimental**. It is subject to change in future releases with no prior notice. +::: + +## Adding plugins + +[Astro Integrations](/en/reference/configuration-reference/#integrations) can add plugins in [the `astro:config:setup` hook](/en/reference/integrations-reference/#astroconfigsetup) using the `addDevOverlayPlugin` method. + +```ts title="integrations.js" +/** + * @type {() => import('astro').AstroIntegration} + */ +export default () => ({ + name: "my-integration", + hooks: { + "astro:config:setup": ({ addDevOverlayPlugin }) => { + addDevOverlayPlugin("./my-plugin.js"); + }, + }, +}); +``` + +## Structure of a plugin + +A plugin is a `.js` or `.ts` file that default exports an object with the following required properties: + +```ts title="src/my-plugin.js" +export default { + id: 'super-plugin', + name: 'My Super Plugin', + icon: '...', + init(canvas, eventTarget) { + eventTarget.dispatchEvent( + new CustomEvent('plugin-notification', { + detail: { + state: true, + }, + }) + ); + } +} +``` + + +### `id: string` + +A unique identifier for the plugin. This will be used to uniquely identify the plugin in hooks and events. + +```ts title="src/my-plugin.js" {2} +export default { + id: 'my-plugin', + // ... +} +``` + +### `name: string` + +The name of the plugin. This will be shown to users whenever the plugin needs to be referenced using a human-readable name. + +```ts title="src/my-plugin.js" {2} +export default { + // ... + name: 'My Plugin', + // ... +} +``` + +### `icon: Icon` + +The icon of the plugin. This will be used to display the plugin in the UI. This can either be an icon from [the icon list](#icons), or a string containing the SVG markup of the icon. + +```ts title="src/my-plugin.js" {2} +export default { + // ... + icon: '...', // or 'astro:logo' +} +``` + +### `init: (canvas: ShadowRoot, eventTarget: EventTarget) => void` + +This is the core part of the plugin. This function will be called when the plugin is loaded, which will either be when the browser is idle or when the user clicks on the plugin in the UI. + +The function receives two arguments: + +#### `canvas` + +A ShadowRoot that the plugin can use to render its UI. Every plugin receive its own dedicated ShadowRoot for rendering its UI. Additionally, the parent element is positioned using `position: absolute;` and as such, the plugin UI automatically won't affect the layout of the page. + +```ts +export default { + id: 'super-plugin', + name: 'My Super Plugin', + icon: '...', + init(canvas) { + canvas.appendChild(document.createTextNode('Hello World!')) + } +} +``` + +#### `eventTarget` + +An [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) that can be used to send and receive events from the dev overlay. + +### `beforeTogglingOff` + +This optional function will be called when the user clicks on the plugin icon in the UI to toggle off the plugin. This function can be used, for example, to perform cleanup operations, do an animation, or to ask the user for confirmation before toggling off the plugin. + +If a falsy value is returned, the toggling off will be cancelled and the plugin will stay enabled. + +```ts title="src/my-plugin.js" {2} +export default { + // ... + beforeTogglingOff() { + const confirmation = window.confirm('Are you sure you want to disable this plugin?'); + return confirmation; + } +} +``` + +#### canvas + +The ShadowRoot of the plugin, can be used to render any UI needed. + +## Client-side Events + +Using the [`eventTarget`](#eventtarget) argument on the [`init`](#init-canvas-shadowroot-eventtarget-eventtarget--void) hook, plugins can send and receive events from the dev overlay. The following events are available: + +### `plugin-toggled` + +This event is fired when the user clicks on the plugin icon in the dev overlay bar. + +```ts title="src/my-plugin.js" {3-6} + export default { + // ... + init(canvas, eventTarget) { + eventTarget.addEventListener('plugin-toggled', (event) => { + if (event.detail.state === true) { + console.log("The plugin is now enabled!") + } + }) + } + } +``` + +#### `state: boolean` + +Indicates whether or not the plugin is enabled after the user's click. + +### `toggle-notification` + +This event can be sent to inform the user that the plugin requires attention. + +```ts title="src/my-plugin.js" {3-6} + export default { + // ... + init(canvas, eventTarget) { + eventTarget.dispatchEvent( + new CustomEvent('toggle-notification', { + detail: { + state: true, + }, + }) + ); + } + } +``` + +#### `state: boolean` + +Indicates whether or not the plugin has a notification for the user. When `true`, the plugin icon will be highlighted using a red dot. Conversely, when `false`, the highlight will be removed. If this property is not specified, `true` will be assumed. + +### `toggle-plugin` + +This event can be sent from your plugin to change the state of your plugin. This can be useful, for instance, to implement a "Close" button in your plugin's UI. + +```ts title="src/my-plugin.js" {3-6} + export default { + // ... + init(canvas, eventTarget) { + eventTarget.dispatchEvent( + new CustomEvent('toggle-plugin', { + detail: { + state: false, + }, + }) + ); + } + } +``` + +#### `state: boolean` + +Indicates whether or not the plugin should be enabled. When `true`, the plugin will be enabled. Conversely, when `false`, the plugin will be disabled. If this property is not specified, `true` will be assumed. + +## Client-Server Communication + +Using [Vite's methods for client-server communication](https://vitejs.dev/guide/api-plugin.html#client-server-communication), dev overlay plugins can communicate with the server. + +In addition to being able to send and receive custom messages, the dev overlay also sends the following messages, where `PLUGIN_ID` is the [plugin's ID](#id-string): + +### `astro-dev-overlay:PLUGIN_ID:initialized` + +This message is sent when the plugin is initialized. The data for this message is empty. + +```ts title="integration.ts" +{ + // ... + "astro:server:setup": ({ server }) => { + server.ws.on("astro-dev-overlay:super-plugin:initialized", () => { + console.log("My plugin was initialized!"); + }); + }, + // ... +} +``` + +### `astro-dev-overlay:PLUGIN_ID:toggled` + +This message is sent when the user clicks on the plugin icon in the UI. The data for this message is a boolean indicating whether the plugin is enabled or not. + +```ts title="integration.ts" +{ + // ... + "astro:server:setup": ({ server }) => { + server.ws.on("astro-dev-overlay:super-plugin:toggled", (data) => { + console.log(`My plugin is now ${data.state ? "enabled" : "disabled"}!`); + }); + }, + // ... +} +``` + +:::note +The built-in `connection` event from Vite fires **before** dev overlay plugins are initialized and therefore cannot be used directly by plugins. Instead, use the `astro-dev-overlay:PLUGIN_ID:init` event. +::: + +## UI Toolkit + +The dev overlay includes a set of web components that can be used to build plugins with a consistent look and feel. + +### `astro-dev-overlay-window` + +Shows a window with optionally a title and an icon. + +`window-title` is a string that will be shown at the top of the overlay window. `window-icon` can either be a string of a SVG file or an icon from [the icon list](#icons). + +The slot of the component will be used as the content of the window. + +```html + +

My content

+
+``` + +### `astro-dev-overlay-card` + +Shows a card with optionally an [`icon`](#icons). Optionally, if a `link` is passed, the card will be clickable and will open the link in a new tab. + +The slot of the component will be used as the content of the card. + +```html +Report an issue +``` + +### `astro-dev-overlay-highlight` + +Can be used to highlight an element on the page. In most cases, you'll want to position and resize this element using the `top`, `left`, `width` and `height` CSS properties to match the element you want to highlight. An [icon](#icons) can also be specified using the `icon` attribute and will be shown in the top right corner of the highlight. + +```html + + +``` + +```ts +const elementToHighlight = document.querySelector('h1'); +const rect = elementToHighlight.getBoundingClientRect(); + +const highlight = document.createElement('astro-dev-overlay-highlight'); + +highlight.style.top = `${Math.max(rect.top + window.scrollY - 10, 0)}px`; +highlight.style.left = `${Math.max(rect.left + window.scrollX - 10, 0)}px`; +highlight.style.width = `${rect.width + 15}px`; +highlight.style.height = `${rect.height + 15}px`; +highlight.icon = 'astro:logo'; +``` + +### `astro-dev-overlay-tooltip` + +Shows a tooltip with different sections. This component is set to `display: none;` by default and can be made visible using a `data-show="true"` attribute. + +Sections are defined using the `sections` property. This property is an array of objects with the following shape: + +```ts +{ + title?: string; // Title of the section + inlineTitle?: string; // Title of the section, shown inline next to the title + icon?: Icon; // Icon of the section + content?: string; // Content of the section + clickAction?: () => void | Promise; // Action to perform when clicking on the section + clickDescription?: string; // Description of the action to perform when clicking on the section +} +``` + +```ts +const tooltip = document.createElement('astro-dev-overlay-tooltip'); + +tooltip.sections = [{ + title: 'My section', + icon: 'astro:logo', + content: 'My content', + clickAction: () => { + console.log('Clicked!') + }, + clickDescription: 'Click me!' +}] +``` + +This component is often combined with the `astro-dev-overlay-highlight` component to show a tooltip when hovering a highlighted element: + +```ts +const highlight = document.createElement('astro-dev-overlay-highlight'); + +// Position the highlight... + +const tooltip = document.createElement('astro-dev-overlay-tooltip'); + +// Add sections to the tooltip... + +highlight.addEventListener('mouseover', () => { + tooltip.dataset.show = 'true'; +}); + +highlight.addEventListener('mouseout', () => { + tooltip.dataset.show = 'false'; +}); +``` + +### Icons + +Currently, the following icons are available and can be used in any component that accepts an icon: + +- `astro:logo` +- `warning` + +In addition to these included icons, you can also pass a string containing the SVG markup of the icon you want to use. + +```html +Read more in the Astro Docs! +``` diff --git a/src/content/docs/en/reference/errors/no-adapter-installed.mdx b/src/content/docs/en/reference/errors/no-adapter-installed.mdx index d51681d6eba50..7bfe0bf04abd6 100644 --- a/src/content/docs/en/reference/errors/no-adapter-installed.mdx +++ b/src/content/docs/en/reference/errors/no-adapter-installed.mdx @@ -20,6 +20,5 @@ To use server-side rendering, an adapter needs to be installed so Astro knows ho **See Also:** - [Server-side Rendering](/en/guides/server-side-rendering/) -- [Adding an Adapter](/en/guides/server-side-rendering/#adding-an-adapter) diff --git a/src/content/docs/en/reference/errors/static-client-address-not-available.mdx b/src/content/docs/en/reference/errors/static-client-address-not-available.mdx index db0bb2c9da644..c265bf8f858b3 100644 --- a/src/content/docs/en/reference/errors/static-client-address-not-available.mdx +++ b/src/content/docs/en/reference/errors/static-client-address-not-available.mdx @@ -21,7 +21,7 @@ The `Astro.clientAddress` property is only available when [Server-side rendering To get the user's IP address in static mode, different APIs such as [Ipify](https://www.ipify.org/) can be used in a [Client-side script](/en/guides/client-side-scripts/) or it may be possible to get the user's IP using a serverless function hosted on your hosting provider. **See Also:** -- [Enabling SSR in Your Project](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) +- [Enabling SSR in Your Project](/en/guides/server-side-rendering/) - [Astro.clientAddress](/en/reference/api-reference/#astroclientaddress) diff --git a/src/content/docs/en/reference/errors/static-redirect-not-available.mdx b/src/content/docs/en/reference/errors/static-redirect-not-available.mdx index 33cea00ba861d..f2e490db6d751 100644 --- a/src/content/docs/en/reference/errors/static-redirect-not-available.mdx +++ b/src/content/docs/en/reference/errors/static-redirect-not-available.mdx @@ -25,7 +25,7 @@ The `Astro.redirect` function is only available when [Server-side rendering](/en To redirect on a static website, the [meta refresh attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) can be used. Certain hosts also provide config-based redirects (ex: [Netlify redirects](https://docs.netlify.com/routing/redirects/)). **See Also:** -- [Enabling SSR in Your Project](/en/guides/server-side-rendering/#enabling-ssr-in-your-project) +- [Enabling SSR in Your Project](/en/guides/server-side-rendering/) - [Astro.redirect](/en/reference/api-reference/#astroredirect) diff --git a/src/content/docs/en/reference/image-service-reference.mdx b/src/content/docs/en/reference/image-service-reference.mdx index 10a13f5215541..8e209dfe06070 100644 --- a/src/content/docs/en/reference/image-service-reference.mdx +++ b/src/content/docs/en/reference/image-service-reference.mdx @@ -62,7 +62,7 @@ export default service; ### Local Services -To create your own local service, you can point to the [built-in endpoint](https://github.com/withastro/astro/blob/main/packages/astro/src/assets/image-endpoint.ts) (`/_image`), or you can additionally create your own endpoint that can call the service's methods. +To create your own local service, you can point to the [built-in endpoint](https://github.com/withastro/astro/blob/main/packages/astro/src/assets/endpoint/generic.ts) (`/_image`), or you can additionally create your own endpoint that can call the service's methods. ```js import type { LocalImageService, AstroConfig } from "astro"; @@ -88,7 +88,7 @@ const service: LocalImageService = { quality: params.get('q'), }; }, - transform(buffer: Buffer, options: { src: string, [key: string]: any }, imageConfig): { data: Buffer, format: OutputFormat } { + transform(buffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig): { data: Uint8Array, format: OutputFormat } { const { buffer } = mySuperLibraryThatEncodesImages(options); return { data: buffer, @@ -197,7 +197,7 @@ This hook parses the generated URLs by `getURL()` back into an object with the d **Required for local services only; unavailable for external services** -`transform(buffer: Buffer, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']): { data: Buffer, format: OutputFormat }` +`transform(buffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']): { data: Uint8Array, format: OutputFormat }` This hook transforms and returns the image and is called during the build to create the final asset files. @@ -214,7 +214,7 @@ This hook returns all additional attributes used to render the image as HTML, ba ### `getSrcSet()` Experimental -**Optional for both local and external services.** +**Optional for both local and external services.** `getSrcSet?: (options: ImageTransform, imageConfig: AstroConfig['image']): SrcSetValue[] | Promise;` diff --git a/src/content/docs/en/reference/integrations-reference.mdx b/src/content/docs/en/reference/integrations-reference.mdx index 55f9b960b4783..9d20f7b779fd5 100644 --- a/src/content/docs/en/reference/integrations-reference.mdx +++ b/src/content/docs/en/reference/integrations-reference.mdx @@ -30,6 +30,8 @@ interface AstroIntegration { addRenderer: (renderer: AstroRenderer) => void; addWatchFile: (path: URL | string) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; + addMiddleware: (middleware: AstroIntegrationMiddleware) => void; + addDevOverlayPlugin: (pluginEntrypoint: string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entryPoint: string }) => void; logger: AstroIntegrationLogger; @@ -74,6 +76,8 @@ interface AstroIntegration { updateConfig: (newConfig: Record) => void; addRenderer: (renderer: AstroRenderer) => void; addClientDirective: (directive: ClientDirectiveConfig) => void; + addMiddleware: (middleware: AstroIntegrationMiddleware) => void; + addDevOverlayPlugin: (pluginEntrypoint: string) => void; addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entryPoint: string }) => void; @@ -214,6 +218,95 @@ declare module 'astro' { } ``` +#### `addDevOverlayPlugin` option + + + +**Type:** `(pluginEntrypoint: string) => void;` + +Adds a [custom dev overlay plugin](/en/reference/dev-overlay-plugin-reference/). + +Example usage: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; +import devOverlayIntegration from './astro-dev-overlay-plugin/integration.js' + +// https://astro.build/config +export default defineConfig({ + integrations: [ + devOverlayIntegration() + ], +}); +``` + +```js title="astro-dev-overlay-plugin/integration.js" +/** + * @type {() => import('astro').AstroIntegration} + */ +export default () => ({ + name: "dev-overlay-plugin", + hooks: { + "astro:config:setup": ({ addDevOverlayPlugin }) => { + addDevOverlayPlugin("./astro-dev-overlay-plugin/plugin.js"); + }, + }, +}); +``` + +```js title="astro-dev-overlay-plugin/plugin.js" + +/** + * @type {import('astro').DevOverlayPlugin} + */ +export default { + id: "my-plugin", + name: "My Plugin", + icon: "...", + init() { + console.log("I'm a dev overlay plugin!") + }, +}; +``` +#### `addMiddleware` option + + + +**Type:** `(middleware:` [`AstroIntegrationMiddleware`](https://github.com/withastro/astro/blob/852ac0f75dfca1b2602e9cdbfa0447d9998e2449/packages/astro/src/%40types/astro.ts#L2124-L2127) `) => void;` + +Adds [middleware](/en/guides/middleware/) to run on each request. Takes the `entrypoint` module that contains the middleware, and an `order` to specify whether it should run before (`pre`) other middleware or after (`post`). + +```js title="@my-package/integration.js" +/** + * @type {() => import('astro').AstroIntegration} + */ +export default () => ({ + name: "my-middleware-package", + hooks: { + "astro:config:setup": ({ addMiddleware }) => { + addMiddleware({ + entrypoint: '@my-package/middleware', + order: 'pre' + }); + }, + }, +}); +``` + +Middleware is defined in a package with an `onRequest` function, as with user-defined middleware. + +```js title="@my-package/middleware.js" +import { defineMiddleware } from 'astro:middleware'; + +export const onRequest = defineMiddleware(async (context, request) => { + if(context.url.pathname === '/some-test-path') { + return Response.json({ + ok: true + }); + } +}); +``` + #### `injectRoute` option **Type:** `({ pattern: string, entryPoint: string }) => void;` @@ -613,3 +706,7 @@ integrations: [ examplePreset() ] ``` + +## Community Resources + +[Build your own Astro Integrations](https://www.freecodecamp.org/news/how-to-use-the-astro-ui-framework/#chapter-8-build-your-own-astro-integrations-1) - by Emmanuel Ohans on FreeCodeCamp diff --git a/src/content/docs/en/reference/publish-to-npm.mdx b/src/content/docs/en/reference/publish-to-npm.mdx index c5791f2338543..578163002a681 100644 --- a/src/content/docs/en/reference/publish-to-npm.mdx +++ b/src/content/docs/en/reference/publish-to-npm.mdx @@ -259,7 +259,7 @@ Share your hard work by adding your integration to our [integrations library](ht ### `package.json` data -The library is automatically updated nightly, pulling in every package published to NPM with the `astro-component` or `withastro` keyword. +The library is automatically updated weekly, pulling in every package published to NPM with the `astro-component` or `withastro` keyword. The integrations library reads the `name`, `description`, `repository`, and `homepage` data from your `package.json`. diff --git a/src/content/docs/en/tutorial/3-components/1.mdx b/src/content/docs/en/tutorial/3-components/1.mdx index 1cd2cebdd1b9d..f2bb4ed002918 100644 --- a/src/content/docs/en/tutorial/3-components/1.mdx +++ b/src/content/docs/en/tutorial/3-components/1.mdx @@ -7,7 +7,6 @@ description: |- i18nReady: true --- import Badge from '~/components/Badge.astro'; -import Blanks from '~/components/tutorial/Blanks.astro'; import Box from '~/components/tutorial/Box.astro'; import Checklist from '~/components/Checklist.astro'; import MultipleChoice from '~/components/tutorial/MultipleChoice.astro'; @@ -89,7 +88,7 @@ This allows you to get started quickly with any working code, often duplicated t - + ### Test your knowledge diff --git a/src/content/docs/en/tutorial/3-components/3.mdx b/src/content/docs/en/tutorial/3-components/3.mdx index ed8c867b656ee..30cb22677dd86 100644 --- a/src/content/docs/en/tutorial/3-components/3.mdx +++ b/src/content/docs/en/tutorial/3-components/3.mdx @@ -11,8 +11,6 @@ i18nReady: true import Badge from '~/components/Badge.astro'; import Box from '~/components/tutorial/Box.astro'; import Checklist from '~/components/Checklist.astro'; -import MultipleChoice from '~/components/tutorial/MultipleChoice.astro'; -import Option from '~/components/tutorial/Option.astro'; import PreCheck from '~/components/tutorial/PreCheck.astro'; @@ -52,7 +50,7 @@ Since your site will be viewed on different devices, it's time to create a page - + ## Try it yourself - Update your pages diff --git a/src/content/docs/en/tutorial/5-astro-api/4.mdx b/src/content/docs/en/tutorial/5-astro-api/4.mdx index 60d95e8c5fddc..45a9280686c03 100644 --- a/src/content/docs/en/tutorial/5-astro-api/4.mdx +++ b/src/content/docs/en/tutorial/5-astro-api/4.mdx @@ -38,7 +38,7 @@ Individuals can subscribe to your feed in a feed reader, and receive a notificat ```shell - pnpm install @astrojs/rss + pnpm add @astrojs/rss ``` diff --git a/src/content/docs/en/tutorial/6-islands/3.mdx b/src/content/docs/en/tutorial/6-islands/3.mdx index aa26619eab1b5..6481100c1aa14 100644 --- a/src/content/docs/en/tutorial/6-islands/3.mdx +++ b/src/content/docs/en/tutorial/6-islands/3.mdx @@ -59,7 +59,7 @@ Welcome to the universe, astronaut. 👩🏼‍🚀👨🏿‍🚀🧑‍🚀 ## Next Steps -Continue with either of our tutorial extensions to [add view transitions to this project](/en/tutorials/add-view-transitions/) or to [add a content collection to manage your plog posts](/en/tutorials/add-content-collections/) +Continue with either of our tutorial extensions to [add view transitions to this project](/en/tutorials/add-view-transitions/) or to [add a content collection to manage your blog posts](/en/tutorials/add-content-collections/) [Start a new Astro project](/en/getting-started/) diff --git a/src/content/docs/en/tutorials/add-content-collections.mdx b/src/content/docs/en/tutorials/add-content-collections.mdx index bebb12371c09c..eeb5bf881f4b4 100644 --- a/src/content/docs/en/tutorials/add-content-collections.mdx +++ b/src/content/docs/en/tutorials/add-content-collections.mdx @@ -110,10 +110,10 @@ The steps below show you how to extend the final product of the Build a Blog tut ```shell # Upgrade to Astro v3.x - pnpm install astro@latest + pnpm add astro@latest # Example: upgrade the blog tutorial Preact integration - pnpm install @astrojs/preact@latest + pnpm add @astrojs/preact@latest ``` diff --git a/src/content/docs/en/tutorials/add-view-transitions.mdx b/src/content/docs/en/tutorials/add-view-transitions.mdx index 7ce90e8b87d05..2695c397b8825 100644 --- a/src/content/docs/en/tutorials/add-view-transitions.mdx +++ b/src/content/docs/en/tutorials/add-view-transitions.mdx @@ -29,7 +29,7 @@ This tutorial uses the [Build a Blog tutorial's finished project](https://github You can instead follow these steps with your own Astro project, but you will need to adjust the instructions for your codebase. -We recommend using our sample project to complete this short tutorial first. Then, you can use what you have learned to create content collections in your own project. +We recommend using our sample project to complete this short tutorial first. Then, you can use what you have learned to create view transitions in your own project. ## Build a Blog Tutorial Code @@ -116,10 +116,10 @@ The steps below show you how to extend the final product of the Build a Blog tut ```shell # Upgrade to Astro v3.x - pnpm install astro@latest + pnpm add astro@latest # Example: upgrade the blog tutorial Preact integration - pnpm install @astrojs/preact@latest + pnpm add @astrojs/preact@latest ``` @@ -184,7 +184,7 @@ The steps below show you how to extend the final product of the Build a Blog tut With view transitions, some scripts may no longer re-run after page navigation like they do with full-page browser refreshes. There are two events during client-side routing that you can listen for, and fire events when they occur: [`astro:page-load`](/en/guides/view-transitions/#astropage-load) and [`astro:after-swap`](/en/guides/view-transitions/#astroafter-swap). -4. Make the script controling the `` mobile menu component available after navigating to a new page. +4. Make the script controlling the `` mobile menu component available after navigating to a new page. To make your mobile menu interactive after navigating to a new page, add the following code that listens for the `astro:page-load` event which runs at the end of page navigation, and in response, runs the existing script to make the hamburger menu function when clicked: @@ -431,4 +431,4 @@ With view transitions, some scripts may no longer re-run after page navigation l There is still so much more to explore! See our [full View Transitions Guide](/en/guides/view-transitions/) for more things you can do with view transitions. -For the full example of the blog tutorial using view transitions, see the [View Transitions branch](https://github.com/withastro/blog-tutorial-demo/tree/view-transitions) of the tutorial repo. \ No newline at end of file +For the full example of the blog tutorial using view transitions, see the [View Transitions branch](https://github.com/withastro/blog-tutorial-demo/tree/view-transitions) of the tutorial repo. diff --git a/src/content/docs/es/core-concepts/astro-components.mdx b/src/content/docs/es/core-concepts/astro-components.mdx index 1ff242da4c15f..8e2329fff6b74 100644 --- a/src/content/docs/es/core-concepts/astro-components.mdx +++ b/src/content/docs/es/core-concepts/astro-components.mdx @@ -253,6 +253,11 @@ Ten en cuenta que los slots con nombre deben ser hijos inmediatos del componente Los slots con nombre también se pueden pasar a [componentes de framework](/es/core-concepts/framework-components/) en archivos Astro. ::: +:::note +Un nombre de slot de Astro no puede ser generado dinámicamente, tal como dentro de una función map. Si esta característica es necesaria dentro de componentes de framework UI, podría ser mejor generar estos slots dinámicos dentro del framework mismo. +::: + + ### Contenido alternativo para slots Los slots también pueden renderizar **contenido alternativo** en el caso que no reciban datos con `` para emparejar, sea slot con nombre o no. diff --git a/src/content/docs/es/core-concepts/astro-pages.mdx b/src/content/docs/es/core-concepts/astro-pages.mdx index 0bccecac6872d..09b59c55924f9 100644 --- a/src/content/docs/es/core-concepts/astro-pages.mdx +++ b/src/content/docs/es/core-concepts/astro-pages.mdx @@ -3,6 +3,7 @@ title: Páginas description: Introducción a páginas de Astro i18nReady: true --- +import Since from '~/components/Since.astro' Las **páginas** son [componentes de Astro](/es/core-concepts/astro-components/) que se encuentran en la subcarpeta `src/pages/`. Ellas son las responsables de manejar el enrutamiento, la carga de datos y el diseño general de cada página HTML de tu proyecto. @@ -52,6 +53,8 @@ Las páginas de Astro utilizan la extensión `.astro` y tienen las mismas funcio ``` +Una página debe producir un documento HTML completo. Si no se incluye explícitamente, Astro agregará la declaración `` necesaria y el contenido de `` a cualquier componente `.astro` ubicado dentro de `src/pages/` de forma predeterminada. Puedes optar por no participar en este comportamiento en una base por componente marcándolo como una [página parcial](#páginas-parciales). + Para evitar repetir los mismos elementos HTML en cada página, puedes mover los elementos comunes `` y `` a sus propios [componentes de plantilla](/es/core-concepts/layouts/). Puedes usar tantos o tan pocos componentes de plantilla como desees. ```astro title="src/pages/index.astro" {2} // @@ -95,3 +98,75 @@ Los archivos `.html` pueden ser colocados en `src/pages/` y usados directamente Para crear una página de error 404 personalizada, puedes crear un archivo `404.astro` o `404.md` en `/src/pages`. Esto generará una página `404.html` que la mayoría de los [servicios de despliegue](/es/guides/deploy/) encontrarán y usarán. + +## Páginas Parciales + + + +:::caution +Las páginas parciales están destinadas para ser usadas en conjunto con una biblioteca de front-end, como [htmx](https://htmx.org/) o [Unpoly](https://unpoly.com/). También puedes usarlas si te sientes cómodo escribiendo JavaScript de front-end de bajo nivel. Por esta razón, son una característica avanzada. + +Adicionalmente, las páginas parciales no deben ser usadas si el componente contiene estilos o scripts con alcance, ya que estos elementos serán eliminados de la salida HTML. Si necesitas estilos con alcance, es mejor usar páginas regulares, no parciales, junto con una biblioteca de front-end que sepa cómo fusionar el contenido en la cabecera. +::: + +Las páginas parciales son componentes de página ubicados dentro de `src/pages/` que no están destinados a renderizar como páginas completas. + +Como componentes localizados fuera de esta carpeta, estos archivos no incluyen automáticamente la declaración ``, ni ningún contenido de `` como estilos y scripts con alcance. + +Sin embargo, debido a que se encuentran en el directorio especial `src/pages/`, el HTML generado está disponible en una URL correspondiente a su ruta de archivo. Esto permite que una biblioteca de renderizado (por ejemplo, htmx, Stimulus, jQuery) la acceda en el cliente y cargue secciones de HTML dinámicamente en una página sin una actualización del navegador o navegación de página. + +Las páginas parciales, cuando se combinan con una biblioteca de renderizado, proporcionan una alternativa a las [islas de Astro](/es/concepts/islands/) y [etiquetas ` + + +
+
Objetivo aquí
+ +
+``` + +La página parcial `.astro` debe existir en la ruta de archivo correspondiente e incluir una exportación que defina la página como parcial: + +```astro title="src/pages/partials/clicked.astro" {2} +--- +export const partial = true; +--- +
¡Fui cliqueado!
+``` + +Consulta la [documentación de htmx](https://htmx.org/docs/) para más detalles sobre el uso de htmx. diff --git a/src/content/docs/es/core-concepts/endpoints.mdx b/src/content/docs/es/core-concepts/endpoints.mdx index 274748a85f3ad..2c6334fded30e 100644 --- a/src/content/docs/es/core-concepts/endpoints.mdx +++ b/src/content/docs/es/core-concepts/endpoints.mdx @@ -98,7 +98,7 @@ Pero, a diferencia del modo `static`, cuando configuras el modo `server`, los en :::note -Asegúrate de [habilitar SSR](/es/guides/server-side-rendering/#habilitando-ssr-en-tu-proyecto) antes de probar estos ejemplos. +Asegúrate de [habilitar SSR](/es/guides/server-side-rendering/) antes de probar estos ejemplos. ::: Los endpoints del servidor pueden acceder a `params` sin exportar `getStaticPaths`, y pueden retornar un objeto [`Response`](https://developer.mozilla.org/es/docs/Web/API/Response), lo que te permite establecer códigos de estado y encabezados: diff --git a/src/content/docs/es/editor-setup.mdx b/src/content/docs/es/editor-setup.mdx index 77e82ab0bebc7..c6bcc5e294cb5 100644 --- a/src/content/docs/es/editor-setup.mdx +++ b/src/content/docs/es/editor-setup.mdx @@ -36,6 +36,7 @@ Nuestra increíble comunidad mantiene extensiones para otros editores de código - [Extensión de Nova](https://extensions.panic.com/extensions/sciencefidelity/sciencefidelity.astro/)Comunidad - Provee resaltado de sintaxis y autocompletado para Astro en Nova. - [Vim Plugin](https://github.com/wuelnerdotexe/vim-astro) Comunidad - Provee resaltado de sintaxis, indentación y compatibilidad con folding de código para Astro en Vim o Neovim. - Neovim [LSP](https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#astro) y [TreeSitter](https://github.com/virchau13/tree-sitter-astro) Plugins Comunidad - Provee resaltado de sintaxis, análisis de árboles y autocompletado para Astro en Neovim. +- Emacs - Ve las instrucciones para [Configurar Emacs y Eglot](https://medium.com/@jrmjrm/configuring-emacs-and-eglot-to-work-with-astro-language-server-9408eb709ab0) Comunidad para trabajar con Astro ## Editores de código del navegador diff --git a/src/content/docs/es/guides/backend/google-firebase.mdx b/src/content/docs/es/guides/backend/google-firebase.mdx index ae8d475ac1392..e6ad8e55aacbf 100644 --- a/src/content/docs/es/guides/backend/google-firebase.mdx +++ b/src/content/docs/es/guides/backend/google-firebase.mdx @@ -19,7 +19,7 @@ Consulta nuestra guía independiente para [desplegar en Firebase Hosting](/es/gu ### Prerrequesitos - Un [proyecto de Firebase con una aplicación web configurada](https://firebase.google.com/docs/web/setup). -- Un proyecto de Astro con [renderizado del lado del servidor (SSR)](/es/guides/server-side-rendering/#habilitando-ssr-en-tu-proyecto) habilitado. +- Un proyecto de Astro con [renderizado del lado del servidor (SSR)](/es/guides/server-side-rendering/) habilitado. - Credenciales de Firebase: Necesitarás dos conjuntos de credenciales para conectar Astro a Firebase: - Credenciales de la aplicación web: Estas credenciales serán utilizadas por el lado del cliente de tu aplicación. Puedes encontrarlas en la consola de Firebase en *Project settings > General*. Desplázate hacia abajo hasta la sección **Your apps** y haz clic en el icono de **Web app**. - Credenciales del proyecto: Estas credenciales serán utilizadas por el lado del servidor de tu aplicación. Puedes generarlas en la consola de Firebase en *Project settings > Service accounts > Firebase Admin SDK > Generate new private key*. diff --git a/src/content/docs/es/guides/backend/xata.mdx b/src/content/docs/es/guides/backend/xata.mdx index 1b6f6549e3bb9..d0f2b43bfa699 100644 --- a/src/content/docs/es/guides/backend/xata.mdx +++ b/src/content/docs/es/guides/backend/xata.mdx @@ -99,9 +99,9 @@ const { records } = await xata.db.Posts.getPaginated({ ---
    - {records.map(post) => ( + {records.map((post) => (
  • {post.title}
  • - )} + ))}
``` Es importante tener en cuenta que el SDK necesita ser generado cada vez que tu esquema cambie. Así que, evita hacer cambios a los archivos generados que crea la CLI de Xata porque una vez que el esquema se actualice, tus cambios se sobrescribirán. diff --git a/src/content/docs/es/guides/cms/buttercms.mdx b/src/content/docs/es/guides/cms/buttercms.mdx index 52712d8d8ba00..39a5f49c8de78 100644 --- a/src/content/docs/es/guides/cms/buttercms.mdx +++ b/src/content/docs/es/guides/cms/buttercms.mdx @@ -30,42 +30,42 @@ Para empezar, necesitarás lo siguiente: 1. Crea un archivo `.env` en la raíz de tu proyecto y agrega tu token de API como una variable de entorno: -```ini title=".env" -BUTTER_TOKEN=TU_TOKEN_DE_API_AQUI -``` + ```ini title=".env" + BUTTER_TOKEN=TU_TOKEN_DE_API_AQUI + ``` -:::tip -Lee más sobre [usar variables de entorno](/es/guides/environment-variables/) y archivos `.env` en Astro. -::: + :::tip + Lee más sobre [usar variables de entorno](/es/guides/environment-variables/) y archivos `.env` en Astro. + ::: 2. Instala el SDK de ButterCMS como una dependencia: - - - ```shell - npm install buttercms - ``` - - - ```shell - pnpm install buttercms - ``` - - - ```shell - yarn add buttercms - ``` - - + + + ```shell + npm install buttercms + ``` + + + ```shell + pnpm install buttercms + ``` + + + ```shell + yarn add buttercms + ``` + + 3. Crea un archivo `buttercms.js` en un nuevo directorio `src/lib/` en tu proyecto: -```js title="src/lib/buttercms.js" -import Butter from "buttercms"; + ```js title="src/lib/buttercms.js" + import Butter from "buttercms"; -export const butterClient = Butter(import.meta.env.BUTTER_TOKEN); -``` + export const butterClient = Butter(import.meta.env.BUTTER_TOKEN); + ``` -Esto autentica el SDK usando tu token de API y lo exporta para ser usado en todo tu proyecto. +**Esto autentica el SDK usando tu token de API y lo exporta para ser usado en todo tu proyecto.** ### Obteniendo datos Para obtener contenido, importa este cliente y usa una de sus funciones `retrieve`. diff --git a/src/content/docs/es/guides/cms/contentful.mdx b/src/content/docs/es/guides/cms/contentful.mdx index df91c735f5576..3ed64646fc453 100644 --- a/src/content/docs/es/guides/cms/contentful.mdx +++ b/src/content/docs/es/guides/cms/contentful.mdx @@ -430,7 +430,7 @@ Navega a http://localhost:4321/ y haz clic en uno de tus artículos para asegura #### Renderizado del lado del servidor -Si has [optado por el modo SSR](/es/guides/server-side-rendering/#habilitando-ssr-en-tu-proyecto), usarás una ruta dinámica que usa un parámetro `slug` para obtener los datos de Contentful. +Si has [optado por el modo SSR](/es/guides/server-side-rendering/), usarás una ruta dinámica que usa un parámetro `slug` para obtener los datos de Contentful. Crea un archivo nuevo llamado `[slug].astro` en `src/pages/posts/`. Usa [`Astro.params`](/es/reference/api-reference/#astroparams) para obtener el slug de la URL, luego pásalo a `getEntries`: diff --git a/src/content/docs/es/guides/cms/cosmic.mdx b/src/content/docs/es/guides/cms/cosmic.mdx new file mode 100644 index 0000000000000..8dc71bcec6ddb --- /dev/null +++ b/src/content/docs/es/guides/cms/cosmic.mdx @@ -0,0 +1,240 @@ +--- +title: Cosmic y Astro +description: Agrega contenido a tu proyecto Astro usando Cosmic como CMS +type: cms +service: Cosmic +i18nReady: true +--- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' + + +[Cosmic](https://www.cosmicjs.com/) es un [CMS headless](https://www.cosmicjs.com/headless-cms) que ofrece un panel de administración para gestionar contenido y una API que puede integrarse con una variedad de herramientas frontend. + +## Prerrequisitos + +1. **Un proyecto de Astro**- Si deseas comenzar con un proyecto de Astro nuevo, lee la [guía de instalación](/es/install/auto/). Esta guía sigue una versión simplificada del [Tema de Astro Headless CMS](https://astro.build/themes/details/cosmic-cms-blog/) con [Tailwind CSS](https://tailwindcss.com/) para estilizar. +2. **Una cuenta y un Bucket en Cosmic** - [Crea una cuenta gratuita en Cosmic](https://app.cosmicjs.com/signup) si no tienes una. Después de crear tu cuenta, se te pedirá que crees un nuevo proyecto vacío. También hay disponible una [plantilla Simple de Blog para Astro](https://www.cosmicjs.com/marketplace/templates/simple-astro-blog) (es la misma plantilla que el Tema Astro Headless CMS) para importar automáticamente todo el contenido utilizado en esta guía. +3. **Tus claves de API de Cosmic** - Desde tu panel de Cosmic, necesitarás encontrar tanto el **slug del Bucket** como la **clave de lectura del Bucket** para conectarte a Cosmic. + +## Integrando Cosmic con Astro + + +### Instalando las Dependencias Necesarias + +Agrega el [SDK de Cosmic para JavaScript](https://www.npmjs.com/package/@cosmicjs/sdk) para obtener datos de tu Bucket en Cosmic. + + + + ```shell + npm install @cosmicjs/sdk + ``` + + + ```shell + pnpm add @cosmicjs/sdk + ``` + + + ```shell + yarn add @cosmicjs/sdk + ``` + + + +### Configurando Claves de API + +Crea un archivo `.env` en la raíz de tu proyecto de Astro (si aún no existe). Agrega tanto el **slug del Bucket** como la **clave de lectura del Bucket** disponibles en tu panel de control de Cosmic como variables de entorno públicas. + +```ini title=".env" +PUBLIC_COSMIC_BUCKET_SLUG=EL_SLUG_DE_TU_BUCKET +PUBLIC_COSMIC_READ_KEY=TU_CLAVE_DE_LECTURA +``` + +## Obteniendo Datos de Cosmic + +1. Crea un nuevo archivo llamado `cosmic.js`. Coloca este archivo dentro de la carpeta `src/lib` en tu proyecto. +2. Agrega el siguiente código para obtener datos de Cosmic usando el SDK y tus variables de entorno. + + El siguiente ejemplo crea una función llamada `getAllPosts()` para obtener metadatos de objetos `posts` de Cosmic: + + ```js + // src/lib/cosmic.js + import { createBucketClient } from '@cosmicjs/sdk' + + const cosmic = createBucketClient({ + bucketSlug: import.meta.env.PUBLIC_COSMIC_BUCKET_SLUG, + readKey: import.meta.env.PUBLIC_COSMIC_READ_KEY + }) + + export async function getAllPosts() { + const data = await cosmic.objects + .find({ + type: 'posts' + }) + .props('title,slug,metadata,created_at') + return data.objects + } + ``` + + Lee más sobre [consultas en la documentación de Cosmic](https://www.cosmicjs.com/docs/api/queries). + +3. Importa tu función de consulta en un componente `.astro`. Después de obtener los datos, los resultados de la consulta pueden utilizarse en tu plantilla de Astro. + + El siguiente ejemplo muestra cómo obtener metadatos de los `posts` de Cosmic y pasar estos valores como props a un componente `` para crear una lista de publicaciones de blog: + + ```astro + --- + // src/pages/index.astro + import Card from '../components/Card.astro' + import { getAllPosts } from '../lib/cosmic' + + const data = await getAllPosts() + --- + +
+
    + { + data.map((post) => ( + tag)} + /> + )) + } +
+
+ ``` + + [Mira el código fuente del componente Card](https://github.com/cosmicjs/simple-astro-blog/blob/main/src/components/Card.astro) + +## Construyendo un Blog con Astro y Cosmic + +Puedes gestionar el contenido de tu blog de Astro mediante Cosmic y crear webhooks para volver a implementar automáticamente tu sitio web cuando actualizas o agregas nuevo contenido. + +### Objetos de Contenido de Cosmic + +Las siguientes instrucciones asumen que tienes un **Tipo de Objeto** en Cosmic llamado **posts**. Cada publicación individual de blog es un `post` que se define en el panel de control de Cosmic con los siguientes Metafields: + +1. **Text input** - Autor +2. **Image** - Imagen de portada +3. **Repeater** - Etiquetas + - **Text input** - Título +4. **Text area** - Extracto +5. **Rich Text** - Contenido + +### Mostrando una lista de publicaciones de blog en Astro + +Utilizando el mismo [método de obtención de datos](#obteniendo-datos-de-cosmic) que se muestra anteriormente, importa la consulta `getAllPosts()` desde tu archivo de script y espera a que se obtengan los datos. Esta función proporciona metadatos sobre cada `post` que se pueden mostrar dinámicamente. + +El ejemplo a continuación pasa estos valores a un componente `` para mostrar una lista formateada de publicaciones de blog: + +```astro +--- +// src/pages/index.astro +import Card from '../components/Card.astro' +import { getAllPosts } from '../lib/cosmic' + +const data = await getAllPosts() +--- + +
+
    + { + data.map((post) => ( + tag)} + /> + )) + } +
+
+``` + +### Generando publicaciones individuales de blog con Astro + +Para generar una página individual con contenido completo para cada publicación de blog, crea una [página de enrutamiento dinámico](/es/core-concepts/routing/#rutas-dinámicas) en `src/pages/blog/[slug].astro`. + +Esta página exportará una función `getStaticPaths()` para generar una ruta de página en el `slug` devuelto por cada objeto `post`. Esta función se llama en tiempo de compilación y genera y renderiza todas tus publicaciones de blog de una vez. + +Para acceder a tus datos desde Cosmic: + +- Realiza una consulta a Cosmic dentro de `getStaticPaths()` para obtener datos sobre cada publicación y proporcionarlos a la función. +- Utiliza cada `post.slug` como un parámetro de ruta, creando las URLs para cada publicación de blog. +- Devuelve cada `post` dentro de `Astro.props`, haciendo que los datos de la publicación estén disponibles en la parte de la plantilla HTML del componente de la página para su renderización. + +El marcado HTML a continuación utiliza varios datos de Cosmic, como el título de la publicación, la imagen de portada y el **contenido en texto enriquecido** (contenido completo de la publicación de blog). Utiliza [set:html](/es/reference/directives-reference/#sethtml) en el elemento que muestra el contenido en texto enriquecido de Cosmic para renderizar elementos HTML en la página exactamente como se obtienen de Cosmic. + +```astro +--- +// src/pages/blog/[slug].astro +import { getAllPosts } from '../../lib/cosmic' +import { Image } from 'astro:assets' + +export async function getStaticPaths() { + const data = (await getAllPosts()) || [] + + return data.map((post) => { + return { + params: { slug: post.slug }, + props: { post } + } + }) +} + +const { post } = Astro.props +--- + +
+
+

{post.title}

+
+ {post.metadata.author?.title} +
+ { + post.metadata.cover_image && ( + {`Imagen + ) + } +
+
+``` + +### Publicando tu sitio + +Para desplegar tu sitio web, visita las [guías de despliegue](/es/guides/deploy/) y sigue las instrucciones para tu proveedor de alojamiento preferido. + +#### Reconstruir en actualizaciones de contenido en Cosmic + +Puedes configurar un webhook directamente en Cosmic para desencadenar una nueva implementación de tu sitio en tu plataforma de alojamiento (p. ej. Vercel) cada vez que actualices o añadas objetos de contenido. + +En "Settings" > "webhooks", agrega el endpoint de URL de Vercel y selecciona el Tipo de Objeto que deseas usar para activar el webhook. Haz clic en "Add webhook" para guardarlo. + +##### Netlify + +Para configurar un webhook en Netlify: + +1. Ve a tu panel de control del sitio y haz clic en **Build & deploy**. +2. En la pestaña de **Continuous Deployment**, busca la sección de **Build hooks** y haz clic en **Add build hook**. +3. Proporciona un nombre para tu webhook y selecciona la rama en la que deseas activar la compilación. Haz clic en **Save** y copia la URL generada. + +##### Vercel + +Para configurar un webhook en Vercel: + +1. Ve a tu panel de control del proyecto y haz clic en **Settings**. +2. En la pestaña de **Git**, busca la sección de **Deploy Hooks**. +3. Proporciona un nombre para tu webhook y la rama en la que deseas activar la compilación. Haz clic en **Add** y copia la URL generada. \ No newline at end of file diff --git a/src/content/docs/es/guides/cms/directus.mdx b/src/content/docs/es/guides/cms/directus.mdx index fa7206f6053af..b0a5c84c6d367 100644 --- a/src/content/docs/es/guides/cms/directus.mdx +++ b/src/content/docs/es/guides/cms/directus.mdx @@ -10,9 +10,9 @@ i18nReady: true [Directus](https://directus.io/) es un backend como servicio que se puede utilizar para alojar datos y contenido para tu proyecto de Astro. ## Recursos oficiales -- Consulta la guía oficial, [Comienza a construir un sitio web de Astro con Directus](https://directus.io/guides/get-started-building-an-astro-website-with-directus/). + - Directus proporciona una [plantilla de blog de Astro de ejemplo](https://github.com/directus/examples/tree/main/astro). ## Recursos de la comunidad -- ¡Agrega el tuyo! \ No newline at end of file +- ¡Agrega el tuyo! diff --git a/src/content/docs/es/guides/cms/frontmatter-cms.mdx b/src/content/docs/es/guides/cms/frontmatter-cms.mdx index 1965a3732f324..a01ee15f93540 100644 --- a/src/content/docs/es/guides/cms/frontmatter-cms.mdx +++ b/src/content/docs/es/guides/cms/frontmatter-cms.mdx @@ -32,25 +32,25 @@ Una vez instalado Front Matter CMS, obtendrás un nuevo icono en la barra de act - Como Astro es uno de los frameworks soportados, puedes seleccionarlo de la lista - Registra tus carpetas de contenido, en este caso, la carpeta `src/content/blog`. -:::note -El registro de la carpeta es necesario para que Front Matter CMS sepa dónde puede encontrar y crear tu contenido. Puedes tener varios tipos de carpetas como páginas, blog, docs y muchos más. -::: + :::note + El registro de la carpeta es necesario para que Front Matter CMS sepa dónde puede encontrar y crear tu contenido. Puedes tener varios tipos de carpetas como páginas, blog, docs y muchos más. + ::: - Se te pedirá que introduzcas el nombre de la carpeta. De forma predeterminada, toma el nombre de la carpeta. -:::note -El nombre se usa durante el proceso de creación de nuevo contenido. Por ejemplo, tener varios registros de carpetas te permite elegir el tipo de contenido que deseas crear. -::: + :::note + El nombre se usa durante el proceso de creación de nuevo contenido. Por ejemplo, tener varios registros de carpetas te permite elegir el tipo de contenido que deseas crear. + ::: - Haz clic en **Start the dashboard** para abrir el panel de contenido -:::tip -Una vez que Front Matter CMS es inicializado, puedes abrir el panel de contenido de las siguientes maneras: + :::tip + Una vez que Front Matter CMS es inicializado, puedes abrir el panel de contenido de las siguientes maneras: -- Usando los combinaciones del teclado: alt + d (Windows & Linux) o options + d (macOS) -- Abre la paleta de comandos y busca `Front Matter: Open dashboard` -- Haz clic en el icono de **Front Matter** en la barra de título del panel o en los archivos. -::: + - Usando los combinaciones del teclado: alt + d (Windows & Linux) o options + d (macOS) + - Abre la paleta de comandos y busca `Front Matter: Open dashboard` + - Haz clic en el icono de **Front Matter** en la barra de título del panel o en los archivos. + ::: ### Configuración del proyecto diff --git a/src/content/docs/es/guides/cms/payload.mdx b/src/content/docs/es/guides/cms/payload.mdx index 55b3deb48b069..97b2bfd9ba3ca 100644 --- a/src/content/docs/es/guides/cms/payload.mdx +++ b/src/content/docs/es/guides/cms/payload.mdx @@ -65,57 +65,55 @@ export default Posts; 1. Importa y agrega tanto `Users` (disponible en todos los proyectos de PayloadCMS) como cualquier otra colección (por ejemplo, `Posts`) a las colecciones disponibles en el archivo `payload.config.ts`. -```astro title="src/payload.config.ts" ins={4, 5, 12} -import { buildConfig } from "payload/config"; -import path from "path"; - -import Users from "./collections/Users"; -import Posts from "./collections/Posts"; - -export default buildConfig({ - serverURL: "http://localhost:4321", - admin: { - user: Users.slug, - }, - collections: [Users, Posts], - typescript: { - outputFile: path.resolve(__dirname, "payload-types.ts"), - }, - graphQL: { - schemaOutputFile: path.resolve(__dirname, "generated-schema.graphql"), - }, -}); -``` + ```astro title="src/payload.config.ts" ins={4, 5, 12} + import { buildConfig } from "payload/config"; + import path from "path"; + import Users from "./collections/Users"; + import Posts from "./collections/Posts"; + export default buildConfig({ + serverURL: "http://localhost:4321", + admin: { + user: Users.slug, + }, + collections: [Users, Posts], + typescript: { + outputFile: path.resolve(__dirname, "payload-types.ts"), + }, + graphQL: { + schemaOutputFile: path.resolve(__dirname, "generated-schema.graphql"), + }, + }); + ``` -Esto hará que aparezca una nueva colección llamada "Posts" en tu panel de control de PayloadCMS junto a la colección "Users". + Esto hará que aparezca una nueva colección llamada "Posts" en tu panel de control de PayloadCMS junto a la colección "Users". 2. Ingresa a la colección "Posts" y crea una nueva publicación. Después de guardarla, notarás que la URL de la API aparece en la esquina inferior derecha. 3. Con el servidor de desarrollo en ejecución, abre `http://localhost:4321/api/posts` en tu navegador. Deberías ver un archivo JSON que contiene la publicación que has creado como un objeto. -```json -{ - "docs":[ - { - "id":"64098b16483b0f06a7e20ed4", - "title":"Astro & PayloadCMS Title 🚀", - "content":"Astro & PayloadCMS Content", - "slug":"astro-payloadcms-slug", - "createdAt":"2023-03-09T07:30:30.837Z", - "updatedAt":"2023-03-09T07:30:30.837Z" - } - ], - "totalDocs":1, - "limit":10, - "totalPages":1, - "page":1, - "pagingCounter":1, - "hasPrevPage":false, - "hasNextPage":false, - "prevPage":null, - "nextPage":null -} -``` + ```json + { + "docs":[ + { + "id":"64098b16483b0f06a7e20ed4", + "title":"Astro & PayloadCMS Title 🚀", + "content":"Astro & PayloadCMS Content", + "slug":"astro-payloadcms-slug", + "createdAt":"2023-03-09T07:30:30.837Z", + "updatedAt":"2023-03-09T07:30:30.837Z" + } + ], + "totalDocs":1, + "limit":10, + "totalPages":1, + "page":1, + "pagingCounter":1, + "hasPrevPage":false, + "hasNextPage":false, + "prevPage":null, + "nextPage":null + } + ``` :::tip Por defecto, tanto Astro como PayloadCMS utilizarán el puerto 4321. Es posible que desees cambiar el puerto de PayloadCMS en el archivo `src/server.ts`. No olvides actualizar el `serverURL` en `src/payload.config.ts` también. diff --git a/src/content/docs/es/guides/cms/storyblok.mdx b/src/content/docs/es/guides/cms/storyblok.mdx index 3d0e3471f660d..6247d8089c0f2 100644 --- a/src/content/docs/es/guides/cms/storyblok.mdx +++ b/src/content/docs/es/guides/cms/storyblok.mdx @@ -272,7 +272,7 @@ Para conectar los Bloks recién creados a los componentes de Astro, crea una nue ```astro title="src/storyblok/Page.astro" --- import { storyblokEditable } from '@storyblok/astro' -import StoryblokComponent from '@storyblok/astro/StoryblokComponent.astro' +import StoryblokComponent from '@storyblok/astro/components/StoryblokComponent'; const { blok } = Astro.props --- @@ -453,7 +453,7 @@ Cuando agregues carpetas dentro de Storyblok, inclúyelas en el slug al interact #### Renderizado en el lado del servidor -Si has [optado por el modo de SSR](/es/guides/server-side-rendering/#habilitando-ssr-en-tu-proyecto), utilizarás rutas dinámicas para obtener los datos de la página desde Storyblok. +Si has [optado por el modo de SSR](/es/guides/server-side-rendering/), utilizarás rutas dinámicas para obtener los datos de la página desde Storyblok. Crea un nuevo directorio `src/pages/blog/` y agrega un nuevo archivo llamado `[...slug].astro` con el siguiente código: @@ -542,4 +542,4 @@ Ahora, cada vez que publiques una nueva historia, se desencadenará una nueva co - [Conseguir que el Editor Visual funcione para Storyblok + Astro](https://dev.to/sandrarodgers/getting-the-visual-editor-to-work-for-storyblok-astro-2gja) por Sandra Rodgers - [Astro + Storyblok: previsualización SSR para una edición visual instantánea](https://dev.to/jgierer12/astro-storyblok-ssr-preview-for-instant-visual-editing-3g9m) por Jonas Gierer -- [Astro-Storyblok previsualiza un sitio con la función Branch Deploys de Netlify](https://dev.to/sandrarodgers/astro-storyblok-previews-site-with-netlifys-branch-deploys-feature-44dh) por Sandra Rodgers \ No newline at end of file +- [Astro-Storyblok previsualiza un sitio con la función Branch Deploys de Netlify](https://dev.to/sandrarodgers/astro-storyblok-previews-site-with-netlifys-branch-deploys-feature-44dh) por Sandra Rodgers diff --git a/src/content/docs/es/guides/cms/strapi.mdx b/src/content/docs/es/guides/cms/strapi.mdx index dbca7045ab2b2..04171f194b7cf 100644 --- a/src/content/docs/es/guides/cms/strapi.mdx +++ b/src/content/docs/es/guides/cms/strapi.mdx @@ -318,7 +318,7 @@ Asegúrate de elegir el renderizado adecuado para tu contenido. Para Markdown, c #### Renderizado en el lado del servidor -Si has [optado por el modo SSR](/es/guides/server-side-rendering/#habilitando-ssr-en-tu-proyecto) con `output: server` o `output: hybrid`, [genera tus rutas dinámicas](/es/core-concepts/routing/#modo-servidor-ssr) utilizando el siguiente código: +Si has [optado por el modo SSR](/es/guides/server-side-rendering/) con `output: server` o `output: hybrid`, [genera tus rutas dinámicas](/es/core-concepts/routing/#modo-servidor-ssr) utilizando el siguiente código: Crea el archivo `src/pages/blog/[slug].astro`: diff --git a/src/content/docs/es/guides/cms/tina-cms.mdx b/src/content/docs/es/guides/cms/tina-cms.mdx index 2de5cf00a8bcf..eeb5d443aa452 100644 --- a/src/content/docs/es/guides/cms/tina-cms.mdx +++ b/src/content/docs/es/guides/cms/tina-cms.mdx @@ -38,7 +38,7 @@ Para empezar, necesitarás un proyecto Astro existente. - Cuando se te pregunte "¿Qué framework estás usando?", escoge **Otro**. - Cuando se te pregunte donde se almacenan los archivos del directorio public, presione Enter. - Depués de haber terminado lo anterior, deberías tener una carpeta `.tina` en la raíz de tu proyecto y una carpeta `admin` en tu directorio public. También creará un archivo Markdown en `content/posts/hello-world.md`. + Depués de haber terminado lo anterior, deberías tener una carpeta `.tina` en la raíz de tu proyecto y un archivo `hello-world.md` generado en `content/posts/hello-world.md`. 2. Cambia el script `dev` en `package.json`: @@ -49,7 +49,7 @@ Para empezar, necesitarás un proyecto Astro existente. { "scripts": { "dev": "astro dev", - "dev": "tinacms dev -c 'astro dev'" + "dev": "tinacms dev -c \"astro dev\"" } } ``` @@ -60,7 +60,7 @@ Para empezar, necesitarás un proyecto Astro existente. { "scripts": { "dev": "astro dev", - "dev": "tinacms dev -c 'astro dev'" + "dev": "tinacms dev -c \"astro dev\"" } } ``` @@ -71,7 +71,7 @@ Para empezar, necesitarás un proyecto Astro existente. { "scripts": { "dev": "astro dev", - "dev": "tinacms dev -c 'astro dev'" + "dev": "tinacms dev -c \"astro dev\"" } } ``` @@ -132,7 +132,7 @@ Para empezar, necesitarás un proyecto Astro existente. name: "body", label: "Body", isBody: true, - }, + }, ], }, ], diff --git a/src/content/docs/es/guides/cms/wordpress.mdx b/src/content/docs/es/guides/cms/wordpress.mdx index 55ac484a4ec56..e5da43810766f 100644 --- a/src/content/docs/es/guides/cms/wordpress.mdx +++ b/src/content/docs/es/guides/cms/wordpress.mdx @@ -176,7 +176,7 @@ Para desplegar tu sitio visita nuestras [guías de despliegue](/es/guides/deploy - [Construyendo un sitio web Astro con WordPress como CMS Headless](https://blog.openreplay.com/building-an-astro-website-with-wordpress-as-a-headless-cms/) por Chris Bongers. - [Construyendo con Astro x WordPress](https://www.youtube.com/watch?v=Jstqgklvfnc) en la transmisión de Ben Holmes. - [Construyendo un sitio WordPress Headless con Astro](https://developers.wpengine.com/blog/building-a-headless-wordpress-site-with-astro) por Jeff Everhart -- [Astro y WordPress como API](https://darko.io/posts/wp-as-an-api/) +- [Astro y WordPress como API](https://darko.io/posts/wp-as-an-api/) por Darko Bozhinovski. ## Sitios en Producción diff --git a/src/content/docs/es/guides/configuring-astro.mdx b/src/content/docs/es/guides/configuring-astro.mdx index c4683606cdf0e..389726284c6ac 100644 --- a/src/content/docs/es/guides/configuring-astro.mdx +++ b/src/content/docs/es/guides/configuring-astro.mdx @@ -116,7 +116,8 @@ export default defineConfig({ }) ``` :::note -Propiedades específicas de `import.meta` de Vite, como `import.meta.env` o `import.meta.glob`, _no_ son accesibles desde tu archivo de configuración. Recomendamos alternativas como [dotenv](https://github.com/motdotla/dotenv) o [fast-glob](https://github.com/mrmlnc/fast-glob) para estos respectivos casos de uso. +{/* Necesitas usar aquí porque Vite hace un reemplazo automático en import-meta-env que rompe el renderizado */} +Propiedades específicas de `import.meta` de Vite, como {'import.meta.env'} o `import.meta.glob`, _no_ son accesibles desde tu archivo de configuración. Recomendamos alternativas como [dotenv](https://github.com/motdotla/dotenv) o [fast-glob](https://github.com/mrmlnc/fast-glob) para estos respectivos casos de uso. ::: ## Personalización de nombres de archivos compilados diff --git a/src/content/docs/es/guides/content-collections.mdx b/src/content/docs/es/guides/content-collections.mdx index 9b3b56c8e3fbb..9585fad33bd3f 100644 --- a/src/content/docs/es/guides/content-collections.mdx +++ b/src/content/docs/es/guides/content-collections.mdx @@ -537,206 +537,11 @@ const { Content } = await entry.render(); --- ``` -## Migrando desde el enrutamiento basado en archivos -Esta guía te muestra cómo convertir un proyecto Astro existente con archivos Markdown en la carpeta `src/pages/` a colecciones de contenido. Utiliza el proyecto terminado del [tutorial de construcción de un blog](https://github.com/withastro/blog-tutorial-demo) como ejemplo. - -1. [Actualiza](/es/guides/upgrade-to/v3/) a Astro v3.0 o posterior, y actualiza todas las integraciones a sus últimas versiones. - -2. [Configura TypeScript](/es/guides/content-collections/#configurando-typescript) para las colecciones de contenido. -3. Crea al menos una colección (carpeta en `src/content/`) y mueve tus páginas Markdown y MDX de `src/pages/` a estos subdirectorios de `src/content/`. Las colecciones funcionan mejor cuando todos los archivos de la misma colección tienen propiedades de frontmatter similares. Por lo tanto, elige tu nueva estructura de carpetas para reflejar tipos similares de páginas. - - Por ejemplo, para migrar las [publicaciones de blog en el tutorial](/es/tutorial/2-pages/2/), mueve el contenido de `src/pages/posts/` a `src/content/posts/`. - -4. Crea un archivo `src/content/config.ts` y [define un esquema](/es/guides/content-collections/#definiendo-un-esquema-de-colección) para cada tipo de contenido. Para el blog, solo tenemos un tipo de contenido, `posts`: - - ```ts title="src/content/config.ts" - // Importa las utilidades de `astro:content` - import { z, defineCollection } from "astro:content"; - // Define un `type` y `schema` para cada colección - const postsCollection = defineCollection({ - type: 'content', - schema: z.object({ - title: z.string(), - pubDate: z.date(), - description: z.string(), - author: z.string(), - image: z.object({ - url: z.string(), - alt: z.string() - }), - tags: z.array(z.string()) - }) - }); - // Exporta un único objeto `collections` para registrar tu(s) colección(es) - export const collections = { - posts: postsCollection, - }; - ``` - - :::tip - Si tu editor no reconoce `astro:content`, asegúrate de que estás en la última versión de Astro y prueba a reiniciar el servidor de desarrollo. - ::: - - -5. [Genera las rutas desde tus colecciones](/es/guides/content-collections/#generando-rutas-desde-el-contenido). Dentro de una colección, los archivos Markdown y MDX ya no se convierten automáticamente en páginas utilizando el [enrutamiento basado en archivos](/es/guides/markdown-content/#enrutamiento-basado-en-archivos) de Astro, por lo que debes generar las páginas tú mismo. - - Para el tutorial, crea un `src/pages/posts/[...slug].astro`. Esta página utilizará [enrutamiento dinámico](/es/core-concepts/routing/#rutas-dinámicas) para generar una página para cada entrada de colección. - - Esta página también deberá [consultar tu colección](#consultando-colecciones) para recuperar los slugs de página y hacer que el contenido de la página esté disponible para cada ruta. - - Renderiza tu `` de publicación dentro del diseño para tus páginas Markdown o MDX. Esto te permite especificar un diseño común para todas tus publicaciones. - - ```astro title="src/pages/posts/[...slug].astro" - --- - import { getCollection } from 'astro:content'; - import MarkdownPostLayout from '../../layouts/MarkdownPostLayout.astro'; - - export async function getStaticPaths() { - const blogEntries = await getCollection('posts'); - return blogEntries.map(entry => ({ - params: { slug: entry.slug }, props: { entry }, - })); - } - - const { entry } = Astro.props; - const { Content } = await entry.render(); - --- - - - - ``` - -6. Elimina la definición de `layout` en el frontmatter de cada publicación individual. Tu contenido ahora está envuelto en un diseño cuando se renderiza, y esta propiedad ya no es necesaria. - - ```md title="src/content/post-1.md" del={2} - --- - layout: ../../layouts/MarkdownPostLayout.astro - title: 'Mi Primer Publicación de Blog' - pubDate: 2022-07-01 - ... - --- - ``` - -7. Reemplaza `Astro.glob()` con [`getCollection()`](/es/reference/api-reference/#getcollection) para obtener contenido y metadatos de tus archivos Markdown. También deberás actualizar las referencias al objeto de publicación devuelto, ya que ahora encontrarás tus valores de frontmatter en la propiedad `data`. - - - El índice del blog en el tutorial enumera una tarjeta para cada publicación. Esto se convierte en: - - ```astro title="src/pages/blog.astro" "post.data" "getCollection(\"posts\")" "'/posts/' + post.slug" - --- - import { getCollection } from "astro:content"; - import BaseLayout from "../layouts/BaseLayout.astro"; - import BlogPost from "../components/BlogPost.astro"; - - const pageTitle = "Mi blog de aprendizaje de Astro"; - const allPosts = await getCollection("posts"); - --- - - -

Aquí es donde publicaré sobre mi viaje aprendiendo Astro.

-
    - { - allPosts.map((post) => ( - - )) - } -
-
- ``` - - El tutorial del proyecto de blog también genera dinámicamente una página para cada etiqueta. Esta página ahora se convierte en: - - ```astro title="src/pages/tags/[tag].astro" "post.data" "getCollection(\"posts\")" "post.data.title" "'/posts/' + post.slug" - --- - import { getCollection } from "astro:content"; - import BaseLayout from "../../layouts/BaseLayout.astro"; - import BlogPost from "../../components/BlogPost.astro"; - - export async function getStaticPaths() { - const allPosts = await getCollection("posts"); - const uniqueTags = [...new Set(allPosts.map((post) => post.data.tags).flat())]; - - return uniqueTags.map((tag) => { - const filteredPosts = allPosts.filter((post) => - post.data.tags.includes(tag) - ); - return { - params: { tag }, - props: { posts: filteredPosts }, - }; - }); - } - - const { tag } = Astro.params; - const { posts } = Astro.props; - --- - - -

Publicaciones etiquetadas con {tag}

-
    - { posts.map((post) => ) } -
-
- ``` - - La misma lógica aparece en la página de índice de etiquetas, que se convierte en: - - ```astro title="src/pages/tags/index.astro" "post.data" "getCollection(\"posts\")" - --- - import { getCollection } from "astro:content"; - import BaseLayout from "../../layouts/BaseLayout.astro"; - const allPosts = await getCollection("posts"); - const tags = [...new Set(allPosts.map((post) => post.data.tags).flat())]; - const pageTitle = "Tag Index"; - --- - ... - ``` - - :::note - Cualquier archivo individual Markdown o MDX importado debe ser reemplazado por [`getEntry()`](/es/reference/api-reference/#getentry). - ::: - -8. Actualiza el código que usa la fecha de publicación en el archivo `layouts/MarkdownPostLayout.astro`. - - Previamente, `pubDate` era un string. Ahora, después de introducir tipos para el frontmatter de tus publicaciones, `pubDate` es un `Date`. - Para renderizar la fecha, conviértela en un string: - - ```astro title="src/layouts/MarkdownPostLayout.astro" "frontmatter.pubDate.toDateString()" - ... - -

{frontmatter.pubDate.toDateString()}

-

{frontmatter.description}

-

Escrito por: {frontmatter.author}

- {frontmatter.image.alt} - ... - ``` - - - Por último, el tutorial de proyecto de blog incluye un feed RSS. Esta función también debe usar `getCollection` y el objeto `data`, y convertirse en una función asíncrona para hacerlo: - - ```js title="src/pages/rss.xml.js" {4-5, 10-15} - import rss from "@astrojs/rss"; - import { getCollection } from "astro:content"; - - export async function get() { - const posts = await getCollection('posts'); - return rss({ - title: 'Estudiante de Astro | Blog', - description: 'Mi viaje aprendiendo Astro', - site: 'https://my-blog-site.netlify.app', - items: posts.map((post) => ({ - title: post.data.title, - pubDate: post.data.pubDate, - description: post.data.description, - link: `/posts/${post.slug}/`, - })), - customData: `en-us`, - }); - } - ``` - -Para ver el ejemplo completo del tutorial de blog usando colecciones de contenido, consulta la [rama de Colecciones de Contenido](https://github.com/withastro/blog-tutorial-demo/tree/content-collections) del repositorio del tutorial. +## Migrando desde el Enrutamiento Basado en Archivos +Si tienes un proyecto de Astro existente como un blog, que usa archivos Markdown o MDX en subcarpetas dentro de `src/pages/`, considera migrar los archivos de contenido o datos relacionados a las colecciones de contenido. + +Consulta cómo convertir un ejemplo básico de blog de `src/pages/posts/` a `src/content/posts` en nuestro [tutorial paso a paso](/es/tutorials/add-content-collections/) que utiliza la base de código del [proyecto terminado del tutorial Crear un Blog](https://github.com/withastro/blog-tutorial-demo). ## Modificando el Frontmatter con Remark @@ -759,3 +564,35 @@ const { remarkPluginFrontmatter } = await blogPost.render(); Los pipelines de remark y rehype solo se ejecutan cuando se renderiza tu contenido, lo que explica por qué `remarkPluginFrontmatter` solo está disponible después de llamar a `render()` en tu entrada de contenido. En contraste, `getCollection()` y `getEntry()` no pueden devolver estos valores directamente porque no renderizan tu contenido. +## Trabajando con fechas en el frontmatter + +Muchos formatos de fecha son admitidos en las colecciones de contenido, pero el esquema de tu colección debe coincidir con el formato utilizado en el frontmatter YAML de tu Markdown o MDX. + +YAML usa el estándar [ISO-8601](https://www.iso.org/iso-8601-date-and-time-format.html) para expresar fechas. Utiliza el formato `yyyy-mm-dd` (por ejemplo, `2021-07-28`) junto con un tipo de esquema de `z.date()`: + +```markdown title="src/pages/posts/example-post.md" +--- +title: Mi Publicación de Blog +pubDate: 2021-07-08 +--- +``` + +El formato de fecha se especificará en UTC si no se proporciona una zona horaria. Si necesitas especificar una zona horaria, puedes usar el formato [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). + +```markdown title="src/pages/posts/example-post.md" +--- +title: Mi Publicación de Blog +pubDate: 2021-07-08T12:00:00-04:00 +--- +``` + +Para renderizar solo `YYYY-MM-DD` de la marca de tiempo UTC completa, utiliza el método `slice` de JavaScript para eliminar la marca de tiempo: + +```astro title="src/layouts/ExampleLayout.astro" +--- +const { frontmatter } = Astro.props; +--- +

{frontmatter.title}

+

{frontmatter.pubDate.slice(0,10)}

+``` +Para ver un ejemplo usando `toLocaleDateString` para formatear el día, mes y año, consulta el componente [``](https://github.com/withastro/astro/blob/latest/examples/blog/src/components/FormattedDate.astro) en la plantilla oficial del blog de Astro. diff --git a/src/content/docs/es/guides/deploy.mdx b/src/content/docs/es/guides/deploy.mdx index bda8a1d5ada51..d8d054405f606 100644 --- a/src/content/docs/es/guides/deploy.mdx +++ b/src/content/docs/es/guides/deploy.mdx @@ -78,6 +78,6 @@ De forma predeterminada, el resultado de compilación se colocará en `dist/`. E :::note Antes de implementar tu proyecto de Astro con [SSR (renderizado en el servidor)](/es/guides/server-side-rendering/) habilitado, asegúrate de tener: -- Instalado el [adaptador apropiado](/es/guides/server-side-rendering/#añadiendo-un-adaptador) en tus dependencias (ya sea manualmente, o usando el comando `astro add`, p. ej. `npx astro add netlify`). +- Instalado el [adaptador apropiado](/es/guides/server-side-rendering/) en tus dependencias (ya sea manualmente, o usando el comando `astro add`, p. ej. `npx astro add netlify`). - [Agregado el adaptador](/es/reference/configuration-reference/#adapter) a tu *import* y *default export* en tu archivo `astro.config.mjs` cuando es instalado manualmente. (¡El comando `astro add` se hará cargo de este paso por ti!) ::: diff --git a/src/content/docs/es/guides/deploy/github.mdx b/src/content/docs/es/guides/deploy/github.mdx index 607c84ed3d5bf..c5e9488323cc6 100644 --- a/src/content/docs/es/guides/deploy/github.mdx +++ b/src/content/docs/es/guides/deploy/github.mdx @@ -29,7 +29,8 @@ Astro mantiene la acción oficial `withastro/action` para desplegar tu proyecto :::note No necesitas configuar el parametro `base` si: - - Tu repositorio es nombrado `.github.io`. + - Tu página es servida desde la carpeta raíz. + - Tu repositorio está ubicado en `https://github.com//.github.io`. - Estás usando un dominio personalizado. ::: diff --git a/src/content/docs/es/guides/deploy/gitlab.mdx b/src/content/docs/es/guides/deploy/gitlab.mdx index dbf3d5ba1235a..cd9f747bdbcdd 100644 --- a/src/content/docs/es/guides/deploy/gitlab.mdx +++ b/src/content/docs/es/guides/deploy/gitlab.mdx @@ -14,7 +14,8 @@ Puedes usar [GitLab Pages](https://pages.gitlab.io/) para alojar un proyecto de ## Cómo desplegar 1. Establece el `site` correcto en `astro.config.mjs`. -2. Establece `outDir:public` en `astro.config.mjs`. Este ajuste le indica a Astro que coloque la salida de archivos estáticos al compilar en una carpeta llamada `public`, la cual es requerida por GitLab Pages para los archivos expuestos. +2. Renombra el directorio `public/` a `static`. +3. Establece `outDir:public` en `astro.config.mjs`. Este ajuste le indica a Astro que coloque la salida de archivos estáticos al compilar en una carpeta llamada `public`, la cual es requerida por GitLab Pages para los archivos expuestos. Si estás usando el [directorio `public/`](/es/core-concepts/project-structure/#public) como fuente de archivos estáticos en tu proyecto de Astro, renombralo y usa ese nuevo nombre del directorio en `astro.config.mjs` para el valor de `publicDir`. @@ -24,36 +25,35 @@ Puedes usar [GitLab Pages](https://pages.gitlab.io/) para alojar un proyecto de import { defineConfig } from 'astro/config'; export default defineConfig({ - sitemap: true, - site: 'https://astro.build/', + site: 'https://.gitlab.io', + base: '/' outDir: 'public', publicDir: 'static', }); ``` -3. Crea un archivo llamado `.gitlab-ci.yml` en la raíz de tu proyecto con el siguiente contenido. Esto compilará y desplegará tu proyecto cada vez que realices cambios en el contenido: +4. Crea un archivo llamado `.gitlab-ci.yml` en la raíz de tu proyecto con el siguiente contenido. Esto compilará y desplegará tu proyecto cada vez que realices cambios en el contenido: ```yaml - # La imagén de Docker que será usada para compilar tu app. - image: node:lts - pages: - cache: - paths: - - node_modules/ + # La imagen de Docker que se usará para construir tu app + image: node:lts + + before_script: + - npm ci + script: - # Especifica los pasos involucrados para compilar tu app. - - npm install + # Especifica los pasos involucrados para construir tu app aquí - npm run build artifacts: paths: - # La carpeta que contiene los archivos compilados para publicarse. - # Éste debe llamarse "public". + # El directorio que contiene los archivos construidos para ser publicados. + # Debe llamarse "public". - public only: - # Acciona una nueva compilación y despliegala solo cuando hay cambios en - # las rama(s) siguientes + # Activa una nueva compilación y despliega solo cuando haya un push a la + # rama(s) a continuación - main ``` diff --git a/src/content/docs/es/guides/deploy/microsoft-azure.mdx b/src/content/docs/es/guides/deploy/microsoft-azure.mdx index fcb1fd5f15c53..3558c58a19370 100644 --- a/src/content/docs/es/guides/deploy/microsoft-azure.mdx +++ b/src/content/docs/es/guides/deploy/microsoft-azure.mdx @@ -7,6 +7,8 @@ i18nReady: true [Azure](https://azure.microsoft.com/) es una plataforma en la nube de Microsoft. Puedes desplegar tu proyecto de Astro con el servicio de [Aplicaciones Web Estáticas](https://aka.ms/staticwebapps) de Microsoft. +Esta guía te llevará a través del despliegue de tu sitio de Astro almacenado en GitHub usando Visual Studio Code. Por favor, consulta las guías de Microsoft para usar una [Tarea de Azure Pipelines](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/azure-static-web-app-v0?view=azure-pipelines) para otras configuraciones. + ## Prerrequisitos Para seguir esta guía necesitarás: @@ -21,7 +23,24 @@ Para seguir esta guía necesitarás: 2. Abre la extensión de Aplicaciones Web Estáticas, inicia sesión en Azure, y haz clic en el botón de **+** para crear una nueva Aplicación Web Estática. Se te pedirá que designes la clave de subscripción a usar. -3. Sigue el asistente iniciado por la extensión para darle a tu aplicación un nombre, seleccionar un framework preestablecido y designar la raíz de tu aplicación (usualmente `/`) y la ubicación de los archivos generados `/dist`. El asistente creará y ejecutará una [GitHub Action](https://github.com/features/actions) en tu repositorio dentro del directorio `.github`. +3. Sigue el asistente iniciado por la extensión para darle a tu aplicación un nombre, seleccionar un framework preestablecido y designar la raíz de tu aplicación (usualmente `/`) y la ubicación de los archivos generados `/dist`. Astro no está enlistado en las plantillas integradas de Azure por lo que necesitarás elegir `custom`. El asistente creará y ejecutará una [GitHub Action](https://github.com/features/actions) en tu repositorio dentro del directorio `.github`. La GitHub Action desplegará tu aplicación (puedes ver el progreso en la pestaña de Actions en GitHub). Cuando se complete con éxito, puedes ver tu aplicación en la dirección mostrada en la ventana de progreso de la Extensión de SWA haciendo clic en el botón de **Browse Website** (esto aparecerá después de que la GitHub Action se haya ejecutado). +## Problemas Conocidos +La acción yaml de GitHub que es creada automáticamente asume el uso de node 14. Esto significa que la compilación de Astro fallará. Para resolver esto actualiza el package.json de tus proyectos con este snippet. + +``` + "engines": { + "node": ">=18.0.0" + }, +``` + +## Recursos Oficiales + +- [Documentación de Microsoft Azure Static Web Apps](https://learn.microsoft.com/es-es/azure/static-web-apps/) + +## Recursos de la Comunidad + +- [Despliegue de un sitio web de Astro en Azure Static Web Apps](https://www.blueboxes.co.uk/deploying-an-astro-website-to-azure-static-web-apps) + diff --git a/src/content/docs/es/guides/deploy/netlify.mdx b/src/content/docs/es/guides/deploy/netlify.mdx index 02378f8576f11..9ba860b58e912 100644 --- a/src/content/docs/es/guides/deploy/netlify.mdx +++ b/src/content/docs/es/guides/deploy/netlify.mdx @@ -56,7 +56,7 @@ Si prefieres instalar el adaptador manualmente, sigue los siguientes dos pasos: export default defineConfig({ output: 'server', adapter: netlify({ - + edgeMiddleware: true + + edgeMiddleware: true }), }); ``` diff --git a/src/content/docs/es/guides/deploy/space.mdx b/src/content/docs/es/guides/deploy/space.mdx index 0ed18a93fc774..ba0548ecb399f 100644 --- a/src/content/docs/es/guides/deploy/space.mdx +++ b/src/content/docs/es/guides/deploy/space.mdx @@ -35,9 +35,9 @@ El CLI de Space intentará detectar automáticamente la configuración de tu apl Realiza los siguientes cambios en el archivo `Spacefile` en la raíz de tu proyecto generado por el CLI de Space: - 1. Cambia el motor a `static`. - 2. Agrega el comando de construcción de Astro a la lista de `commands`. - 3. Sirve el directorio `dist` generado por Astro. +1. Cambia el motor a `static`. +2. Agrega el comando de construcción de Astro a la lista de `commands`. +3. Sirve el directorio `dist` generado por Astro. ```yaml title="Spacefile" {6,8,9} # Documentación de Spacefile: https://go.deta.dev/docs/spacefile/v0 diff --git a/src/content/docs/es/guides/environment-variables.mdx b/src/content/docs/es/guides/environment-variables.mdx index b6abd54be35b0..51f5e3249ce97 100644 --- a/src/content/docs/es/guides/environment-variables.mdx +++ b/src/content/docs/es/guides/environment-variables.mdx @@ -99,7 +99,8 @@ const data = fetch(`${import.meta.env.PUBLIC_POKEAPI}/pokemon/squirtle`); ``` :::caution -Debido a que Vite estáticamente reemplaza `import.meta.env`, no puedes acceder a él con claves dinámicas como `import.meta.env[key]`. +{/* Necesitas usar la etiqueta aquí porque Vite hace un reemplazo automático en import-meta-env que rompe la representación */} +Debido a que Vite estáticamente reemplaza {'import.meta.env'}, no puedes acceder a él con claves dinámicas como {'import.meta.env[key]'}. ::: Cuando se utiliza SSR, se puede acceder a las variables de entorno en tiempo de ejecución en función del adaptador SSR que se esté utilizando. Con la mayoría de los adaptadores puedes acceder a las variables de entorno con `process.env`, pero algunos adaptadores funcionan de forma diferente. Para el adaptador Deno, utilizará `Deno.env.get()`. Mira cómo [acceder al runtime de Cloudflare](/es/guides/integrations-guide/cloudflare/#runtime-de-cloudflare) para manejar las variables de entorno cuando utilices el adaptador de Cloudflare. Astro comprobará primero el entorno del servidor en busca de variables, y si no existen, Astro las buscará en los archivos .env. diff --git a/src/content/docs/es/guides/images.mdx b/src/content/docs/es/guides/images.mdx index 074fd367b168b..265d6a7b37d8d 100644 --- a/src/content/docs/es/guides/images.mdx +++ b/src/content/docs/es/guides/images.mdx @@ -6,6 +6,7 @@ i18nReady: true import Since from '~/components/Since.astro'; import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; import Badge from '~/components/Badge.astro'; +import RecipeLinks from "~/components/RecipeLinks.astro"; ¡Astro ofrece varias formas para que uses imágenes en tu sitio, ya sea que estén almacenadas localmente dentro de tu proyecto, enlazadas desde una URL externa o gestionadas en un CMS o CDN! @@ -611,6 +612,8 @@ import stars from "~/stars/docline.png"; La función `getImage()` está destinada a generar imágenes que se utilizarán en otro lugar que no sea directamente en HTML, por ejemplo, en una [Ruta API](/es/core-concepts/endpoints/#endpoints-del-servidor-rutas-de-api). También te permite crear tu propio componente `` personalizado. + + `getImage()` recibe un objeto de opciones con las [mismas propiedades que el componente Image](#propiedades) (excepto `alt`). ```astro @@ -646,6 +649,16 @@ Si la imagen es meramente decorativa (es decir, no contribuye a la comprensión [Sharp](https://github.com/lovell/sharp) es el servicio de imágenes por defecto utilizado para `astro:assets`. +:::note +Cuando se utiliza un [administrador de paquetes estricto](https://pnpm.io/pnpm-vs-npm#npms-flat-tree) como `pnpm`, es posible que debas instalar manualmente Sharp en tu proyecto, aunque sea una dependencia de Astro: + +```bash +pnpm install sharp +``` +::: + +### Configura Squoosh + Si prefieres utilizar [Squoosh](https://github.com/GoogleChromeLabs/squoosh) para transformar tus imágenes, actualiza tu configuración con lo siguiente: ```js title="astro.config.mjs" ins={4-6} @@ -658,13 +671,21 @@ export default defineConfig({ }); ``` -:::note -Cuando se utiliza un [administrador de paquetes estricto](https://pnpm.io/pnpm-vs-npm#npms-flat-tree) como `pnpm`, es posible que debas instalar manualmente Sharp en tu proyecto, aunque sea una dependencia de Astro: +### Configura el servicio no-op de paso -```bash -pnpm install sharp +Si tu [adaptador para el modo `server` o `hybrid`](https://astro.build/integrations/?search=&categories%5B%5D=adapters) no admite la optimización de imágenes integrada de Astro con Squoosh y Sharp (por ejemplo, Deno, Cloudflare), puedes configurar un servicio de imágenes sin acción para permitirte utilizar los componentes `` y ``. Ten en cuenta que Astro no realiza ninguna transformación ni procesamiento de imágenes en estos entornos. Sin embargo, aún puedes disfrutar de otros beneficios de usar `astro:assets`, como la ausencia de Desplazamiento Acumulativo de Diseño (CLS), el atributo `alt` obligatorio y una experiencia de autoría coherente. + +Configura el servicio `passthroughImageService()` para evitar el procesamiento de imágenes de Squoosh y Sharp: + +```js title="astro.config.mjs" ins={4-6} "passthroughImageService" +import { defineConfig, passthroughImageService } from 'astro/config'; + +export default defineConfig({ + image: { + service: passthroughImageService() + } +}); ``` -::: ## Integraciones comunitarias diff --git a/src/content/docs/es/guides/imports.mdx b/src/content/docs/es/guides/imports.mdx index c0dd4bc316a30..bae004f870d50 100644 --- a/src/content/docs/es/guides/imports.mdx +++ b/src/content/docs/es/guides/imports.mdx @@ -219,7 +219,7 @@ Astro es compatible con la carga de archivos WASM directamente en tu aplicación ## Módulos integrados de Node -Recomendamos a los usuarios de Astro que eviten usar los módulos integrados de Node.js (`fs`, `path`, etc.) siempre que sea posible. Astro es compatible con múltiples motores de ejecución usando [adaptadores](/es/guides/server-side-rendering/#añadiendo-un-adaptador). Esto incluye [Deno](https://github.com/denoland/deno-astro-adapter) y [Cloudflare Workers](/es/guides/integrations-guide/cloudflare/) que no son compatibles con los módulos integrados de Node como `fs`. +Recomendamos a los usuarios de Astro que eviten usar los módulos integrados de Node.js (`fs`, `path`, etc.) siempre que sea posible. Astro es compatible con múltiples motores de ejecución usando [adaptadores](/es/guides/server-side-rendering/). Esto incluye [Deno](https://github.com/denoland/deno-astro-adapter) y [Cloudflare Workers](/es/guides/integrations-guide/cloudflare/) que no son compatibles con los módulos integrados de Node como `fs`. El objetivo de Astro es proporcionar alternativas a los módulos integrados comunes de Node.js. Sin embargo, estas alternativas aún no existen. Si _realmente_ necesitas utilizar estos módulos, no queremos detenerlo. Astro es compatible con los módulos integrados de Node.js utilizando el nuevo prefijo `node:`. Si por ejemplo quieres leer un archivo, puedes hacerlo así: diff --git a/src/content/docs/es/guides/integrations-guide.mdx b/src/content/docs/es/guides/integrations-guide.mdx index 4e038b683ce87..59aa749f529d0 100644 --- a/src/content/docs/es/guides/integrations-guide.mdx +++ b/src/content/docs/es/guides/integrations-guide.mdx @@ -77,23 +77,23 @@ Hay tres formas comunes de importar una integración a tu proyecto Astro: 2. Importando tu propia integración desde un archivo local dentro de tu proyecto. 3. Escribiendo tu integración en línea, directamente en tu archivo de configuración. -```js -// astro.config.mjs -import {defineConfig} from 'astro/config'; -import installedIntegration from '@astrojs/vue'; -import localIntegration from './my-integration.js'; - -export default defineConfig({ - integrations: [ - // 1. Importado desde un paquete npm instalado - installedIntegration(), - // 2. Importado desde un archivo JS local - localIntegration(), - // 3. Un objeto en línea - {name: 'namespace:id', hooks: { /* ... */ }}, - ] -}) -``` + ```js + // astro.config.mjs + import {defineConfig} from 'astro/config'; + import installedIntegration from '@astrojs/vue'; + import localIntegration from './my-integration.js'; + + export default defineConfig({ + integrations: [ + // 1. Importado desde un paquete npm instalado + installedIntegration(), + // 2. Importado desde un archivo JS local + localIntegration(), + // 3. Un objeto en línea + {name: 'namespace:id', hooks: { /* ... */ }}, + ] + }) + ``` Consulta la referencia de [API de integración](/es/reference/integrations-reference/) para conocer las diferentes formas en las que puedes escribir una integración. diff --git a/src/content/docs/es/guides/integrations-guide/cloudflare.mdx b/src/content/docs/es/guides/integrations-guide/cloudflare.mdx index 0ba6c98c166cf..27dc4f1af5dae 100644 --- a/src/content/docs/es/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/es/guides/integrations-guide/cloudflare.mdx @@ -2,7 +2,7 @@ type: integration title: '@astrojs/cloudflare' description: Aprende cómo utilizar el adaptador SSR @astrojs/cloudflare para implementar tu proyecto de Astro. -githubURL: 'https://github.com/withastro/astro/tree/main/packages/integrations/cloudflare/' +githubURL: 'https://github.com/withastro/adapters/tree/main/packages/integrations/cloudflare/' hasREADME: true category: adapter i18nReady: true @@ -199,18 +199,25 @@ export default defineConfig({ ### `runtime` -`runtime: "off" | "local"` +`runtime: { mode: "off" | "local", persistTo: string }` -por defecto: `"off"` +por defecto: `{ mode: 'off', persistTo: '' }` Determina si y como el Runtime de Cloudflare es añadido a `astro dev`. El Runtime de Cloudflare incluye [Cloudflare Bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [variables de entorno](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), y el [objeto cf](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Obtén más información sobre [cómo acceder al Runtime de Cloudflare](#runtime-de-cloudflare). -## Acceso al runtime de Cloudflare +La propiedad `mode` define como el runtime es agregado a `astro dev`: + * `local`: utiliza simulaciones de bindings y placeholders estáticos locales. * `off`: no tiene acceso al runtime de Cloudflare usando `astro dev`. Alternativamente, puedes usar [Vista previa con Wrangler](#vista-previa-con-wrangler). +La propiedad `persistTo` define donde el runtime local es persistido cuando se usa `mode: local`. Este valor es un directorio relativo a la ruta de ejecución de `astro dev`. + +El valor predeterminado se establece en `.wrangler/state/v3` para que coincida con la ruta predeterminada que utiliza Wrangler. Esto significa que ambas herramientas pueden acceder y utilizar el estado local. + +Cualquier directorio que se establezca en `persistTo`, `.wrangler` o tu valor personalizado, debe añadirse a `.gitignore`. + ```diff lang="js" // astro.config.mjs import { defineConfig } from 'astro/config'; diff --git a/src/content/docs/es/guides/integrations-guide/deno.mdx b/src/content/docs/es/guides/integrations-guide/deno.mdx index 02030866fd8e2..0b1babbfd9b42 100644 --- a/src/content/docs/es/guides/integrations-guide/deno.mdx +++ b/src/content/docs/es/guides/integrations-guide/deno.mdx @@ -8,4 +8,4 @@ El adaptador Deno permite a Astro implementar tu sitio SSR en objetivos de Deno, Anteriormente, el adaptador Deno era mantenido por Astro, pero ahora es mantenido directamente por Deno. El uso ahora está documentado en el [repositorio del adaptador Deno](https://github.com/denoland/deno-astro-adapter). -Si actualmente estás utilizando este adaptador de Astro, deberás migrar a la nueva versión de Deno o [agregar otro adaptador](/es/guides/server-side-rendering/#añadiendo-un-adaptador) para seguir SSR en tu proyecto. +Si actualmente estás utilizando este adaptador de Astro, deberás migrar a la nueva versión de Deno o [agregar otro adaptador](/es/guides/server-side-rendering/) para seguir SSR en tu proyecto. diff --git a/src/content/docs/es/guides/integrations-guide/markdoc.mdx b/src/content/docs/es/guides/integrations-guide/markdoc.mdx index 0434b9ece0bc4..d20a5280980ce 100644 --- a/src/content/docs/es/guides/integrations-guide/markdoc.mdx +++ b/src/content/docs/es/guides/integrations-guide/markdoc.mdx @@ -486,6 +486,40 @@ Para lograr una experiencia más similar a Markdown, donde los elementos HTML pu Cuando `allowHTML` está habilitado, el marcado HTML dentro de los documentos de Markdoc se representará como elementos HTML reales (incluyendo ` + - -``` + /* ... */ + + ``` 2. Crea `src/pages/index.astro` -Usa las etiquetas `