diff --git a/src/components/LeftSidebar/Sponsors.astro b/src/components/LeftSidebar/Sponsors.astro index 9a70d765c6aa7..e2ceefecbe8a3 100644 --- a/src/components/LeftSidebar/Sponsors.astro +++ b/src/components/LeftSidebar/Sponsors.astro @@ -4,15 +4,9 @@ import UIString from '../UIString.astro';

- -

What is Astro?

Astro is an **all-in-one** **web framework** for building **fast,** **content-focused** websites. @@ -88,7 +93,7 @@ See examples of some of the key concepts and patterns of an Astro site! ## Join our Community -Join us in the [Astro Discord](https://astro.build/chat/) to share with and get help from an active, friendly community! +Join us in the [Astro Discord](https://astro.build/chat) to share with and get help from an active, friendly community! 💬 Say hi in our `#general` channel! diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx deleted file mode 100644 index 96d05cfe90a43..0000000000000 --- a/src/content/docs/en/guides/assets.mdx +++ /dev/null @@ -1,404 +0,0 @@ ---- -title: Assets (Experimental) -description: Learn how to enable experimental asset support in Astro. -i18nReady: false ---- -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -**Built-in optimized asset support** is enabled in Astro behind an experimental flag. This built-in feature will eventually replace the optional `@astrojs/image` integration. - -The new assets experience currently features: - -- A new built-in `` component -- Relative images with automatic optimization in Markdown, [MDX](/en/guides/integrations-guide/mdx/), and [Markdoc](/en/guides/integrations-guide/markdoc/) -- Integration with content collections -- Improved error messages and types - -:::caution -Assets are an experimental Astro feature introduced in v2.1. This API is subject to change before it is marked as stable. -::: - -## Enabling Assets in your Project - -Enabling assets may cause some breaking changes in your project. It may also require some manual changes to take advantage of new features. - -Please check every section below to avoid errors and to get the most out of using the experimental assets option! - -### Update Config - -To enable built-in asset support, add the following lines to your `astro.config.mjs` configuration file: - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - assets: true - } -}); -``` - -When you next run Astro, it will update your `src/env.d.ts` file to configure types for you. To do this manually, replace the `astro/client` reference with `astro/client-image`: - -```ts title="src/env.d.ts" del={1} ins={2} -/// -/// -``` - -### Move your images to `src/assets/` - -Create `src/assets/`, which Astro will recognize as your new assets folder. - -We recommend storing all images to be optimized in the `src/assets/` directory to make use of our official `~/assets` alias, although this location is optional. If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), you can put your images there and we promise we won't break them! But, images can be stored anywhere, including alongside your content, if you prefer. - -Your images can be used by components (`.astro`, `.mdx`, and other UI frameworks) and in Markdown files. - -### Update existing `` tags - -Previously, importing an image would return a simple `string` with the path of the image. With the new `image` features enabled, imported image assets now match the following signature: - -```ts -interface ImageMetadata { - src: string; - width: number; - height: number; - format: string; -} -``` - -You must update the `src` attribute of any existing `` tags, and you may also update other attributes that are now available to you from the imported image. - -```astro title="src/components/MyComponent.astro" ".src" ".width" ".height" del={2,5} ins={3,6} ---- -import rocket from '../images/rocket.svg'; -import rocket from '../assets/images/rocket.svg' ---- -A rocketship in space. -A rocketship in space. -``` - -### Update your Markdown, MDX, and Markdoc files - -Relative images can now be referenced in Markdown, MDX, and Markdoc files. These will automatically be optimized and hashed by Astro's build process. - -This allows you to move your images from the `public/` directory to the new, reserved `src/assets/` directory or move them near your Markdown, MDX, or Markdoc files. (See the URL path of these built images in the example below.) - -Your existing images in `public/` are still valid but are not automatically optimized by Astro's build process. - -```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/" -# My Markdown Page - - -![A starry night sky.](../../assets/stars.png) -A starry night sky. - - -![Astro logo](https://docs.astro.build/assets/logomark-light.png) -Astro logo - - -![A starry night sky.](/images/stars.png) -A starry night sky. -``` - -### Convert from `@astrojs/image` - -**Built-in asset support is incompatible with the `@astrojs/image` integration.** - -:::note[cropping images] -The Assets API does not support image cropping. The current behaviour is to resize images to fit. - -Use the `@astrojs/image` integration if you need support for cropping images. Alternatively, you can use the [`object-fit` CSS property](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) to achieve a similar result. -::: - -To avoid errors in your project, complete the following steps: - -1. Remove the `@astrojs/image` integration. - - You must [remove the integration](/en/guides/integrations-guide/#removing-an-integration) by uninstalling and then removing it from your `astro.config.mjs` file. - -2. Migrate any existing `` components. - - Change all `import` statements from `@astrojs/image/components` to `astro:assets` to use the new built-in `` component. - - Remove any component attributes that are not [currently supported image asset properties](#properties). - - For example `aspectRatio` is no longer supported, as it is now automatically inferred from the `width` and `height` attributes. - - ```astro title="src/components/MyComponent.astro" del= {2,11} ins={3} - --- - import { Image } from '@astrojs/image/components'; - import { Image } from 'astro:assets' - import localImage from "../assets/logo.png"; - const localAlt = "The Astro Logo"; - --- - - {localAlt} - ``` - - -3. Remove any existing `` components - - Currently, the built-in assets feature does not include a `` component. - - Instead, you can use the HTML image attributes `srcset` and `sizes` or the `` tag [for art direction or to create responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction). - - -### Update content collections schemas - -You can now declare images in your frontmatter as their paths relative to the current folder. - -```md title="src/content/blog/my-post.md" ---- -title: "My first blog post" -cover: "./firstpostcover.jpeg" # will resolve to "src/content/blog/firstblogcover.jpeg" -coverAlt: "A photograph of a sunset behind a mountain range" ---- - -This is a blog post -``` - -A new `image` helper for content collections lets you validate the image metadata using Zod. - -```ts title="src/content/config.ts" -import { defineCollection, z } from "astro:content"; - -const blogCollection = defineCollection({ - schema: ({ image }) => z.object({ - title: z.string(), - cover: image().refine((img) => img.width >= 1080, { - message: "Cover image must be at least 1080 pixels wide!", - }), - coverAlt: z.string(), - }), -}); - -export const collections = { - blog: blogCollection, -}; -``` - -The image will be imported and transformed into metadata that matches the signature of imported images, allowing you to pass it as a `src` to `` or `getImage()`. A blog index page might render the cover photo and title of each blog post: - -```astro title="src/pages/blog.astro" {10} ---- -import { Image } from "astro:assets"; -import { getCollection } from "astro:content"; -const allBlogPosts = await getCollection("blog"); ---- - -{ - allBlogPosts.map((post) => ( -
- {post.data.coverAlt} -

- {post.data.title} -

-
- )) -} -``` - -### Allowed domains and remote patterns for remote images - -For security reasons, Astro will not process remote images from all domains by default. You can specify which domains to allow in your `astro.config.mjs` file. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - image: { - domains: ["astro.build"], - } -}); -``` - -Alternatively, you can specify a pattern to match against the `src` attribute of remote images to allow. This can be useful if you want to allow images from a CDN that uses a wildcard subdomain. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - image: { - remotePatterns: [{ hostname: "*.akamaihd.net" }], - } -}); -``` - -The protocol, hostname, pathname, and port of the image URL can be checked using this method. For instance, you could allow only images being served from HTTPs using `{ protocol: "https" }`. - -See [`image.domains`](/en/reference/configuration-reference/#imagedomains-experimental) and [`image.remotePatterns`](/en/reference/configuration-reference/#imageremotepatterns-experimental) for detailed configuration instructions. - -## `astro:assets` module - -Enabling asset support allows you to access the `astro:assets` module. This module exposes the following features: - -- `` (available in `.astro` and `.mdx` files) -- `getImage()` (available in `.astro`, `.mdx`, `.ts`, `.js` on the server) - -:::caution -`` is an Astro component and [can't be used in framework components](/en/core-concepts/framework-components/#can-i-use-astro-components-inside-my-framework-components). - -`getImage()` relies on server-only APIs and breaks the build when used on the client. -::: - -### `` (`astro:assets`) - -The `` component generates an `` tag. - -This component can transform an image's dimensions, file type, and quality to produce an optimized image. The resulting `` tag will include the correct `width` and `height` attributes to avoid Cumulative Layout Shift **(CLS)**. - -:::tip[What is Cumulative Layout Shift?] -CLS is a score that reflects how much content shifted on your page during loading. The ideal number for CLS is as close to zero as possible, which the `Image` component enforces by automatically selecting the correct `width` and `height` for local images. -::: - -Import images from a **relative file path** or [import alias](/en/guides/aliases/) in any component file and then use the import as the `` component's `src` attribute. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; // Image is 1600x900 ---- - - -A description of my image. -``` - -```astro - - -A description of my image. -``` - -#### Properties - -##### width and height - -These properties define the dimensions to use for the image. - -When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. However, both of these properties are required for remote images. - -##### format - -You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) to be used. The default file format used is `webp`. - -##### quality - -`quality` is an optional property that can either be: -- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. -- a number from `0` to `100` (interpreted differently between formats). - -##### alt (required) - -Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. - -This attribute is required for the `` component. This component will throw an error if no alt text is provided. - -If the image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers know to ignore the image. - -##### Additional properties - -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. - -For example, you can provide a `class` to the final `img` element. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; ---- - - - -``` - -```astro - - -``` - -### `getImage()` (`astro:assets`) - -This 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 (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..) -} -``` - -## Using sharp - -By default, Astro uses [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images. - -If you're building a static site or deploying an SSR site to a Node environment, we recommend using [sharp](https://github.com/lovell/sharp), which offers faster performance but requires Node. To use sharp, first install it: - - - - ```shell - npm install sharp - ``` - - - ```shell - pnpm install sharp - ``` - - - ```shell - yarn add sharp - ``` - - - -Then, enable Astro's sharp image service in your config: - -```js title="astro.config.mjs" -import { defineConfig, sharpImageService } from "astro/config"; - -export default defineConfig({ - experimental: { - assets: true, - }, - image: { - service: sharpImageService(), - }, -}); -``` diff --git a/src/content/docs/en/guides/backend/google-firebase.mdx b/src/content/docs/en/guides/backend/google-firebase.mdx index c7f0f32d1c8f8..4509287087200 100644 --- a/src/content/docs/en/guides/backend/google-firebase.mdx +++ b/src/content/docs/en/guides/backend/google-firebase.mdx @@ -190,7 +190,7 @@ import type { APIRoute } from "astro"; import { app } from "../../../firebase/server"; import { getAuth } from "firebase-admin/auth"; -export const get: APIRoute = async ({ request, cookies, redirect }) => { +export const GET: APIRoute = async ({ request, cookies, redirect }) => { const auth = getAuth(app); /* Get token from request headers */ @@ -235,7 +235,7 @@ This is a basic implementation of the login endpoint. You can add more logic to ```ts title="src/pages/api/auth/signout.ts" import type { APIRoute } from "astro"; -export const get: APIRoute = async ({ redirect, cookies }) => { +export const GET: APIRoute = async ({ redirect, cookies }) => { cookies.delete("session", { path: "/", }); @@ -254,7 +254,7 @@ import type { APIRoute } from "astro"; import { getAuth } from "firebase-admin/auth"; import { app } from "../../../firebase/server"; -export const post: APIRoute = async ({ request, redirect }) => { +export const POST: APIRoute = async ({ request, redirect }) => { const auth = getAuth(app); /* Get form data */ @@ -354,8 +354,8 @@ import Layout from "../layouts/Layout.astro"; /* Check if the user is authenticated */ const auth = getAuth(app); -const sessionCookie = Astro.cookies.get("session").value; -if (sessionCookie) { +if (Astro.cookies.has("session")) { + const sessionCookie = Astro.cookies.get("session").value; const decodedCookie = await auth.verifySessionCookie(sessionCookie); if (decodedCookie) { return Astro.redirect("/dashboard"); @@ -431,11 +431,10 @@ import Layout from "../layouts/Layout.astro"; const auth = getAuth(app); /* Check current session */ -const sessionCookie = Astro.cookies.get("session").value; - -if (!sessionCookie) { +if (!Astro.cookies.has("session")) { return Astro.redirect("/signin"); } +const sessionCookie = Astro.cookies.get("session").value; const decodedCookie = await auth.verifySessionCookie(sessionCookie); const user = await auth.getUser(decodedCookie.uid); @@ -473,8 +472,8 @@ import Layout from "../layouts/Layout.astro"; /* Check if the user is authenticated */ const auth = getAuth(app); -const sessionCookie = Astro.cookies.get("session").value; -if (sessionCookie) { +if (Astro.cookies.has("session")) { + const sessionCookie = Astro.cookies.get("session").value; const decodedCookie = await auth.verifySessionCookie(sessionCookie); if (decodedCookie) { return Astro.redirect("/dashboard"); @@ -586,7 +585,7 @@ import type { APIRoute } from "astro"; import { app } from "../../../firebase/server"; import { getFirestore } from "firebase-admin/firestore"; -export const post: APIRoute = async ({ request, redirect }) => { +export const POST: APIRoute = async ({ request, redirect }) => { const formData = await request.formData(); const name = formData.get("name")?.toString(); const age = formData.get("age")?.toString(); @@ -628,7 +627,7 @@ import { getFirestore } from "firebase-admin/firestore"; const db = getFirestore(app); const friendsRef = db.collection("friends"); -export const post: APIRoute = async ({ params, redirect, request }) => { +export const POST: APIRoute = async ({ params, redirect, request }) => { const formData = await request.formData(); const name = formData.get("name")?.toString(); const age = formData.get("age")?.toString(); @@ -660,7 +659,7 @@ export const post: APIRoute = async ({ params, redirect, request }) => { return redirect("/dashboard"); }; -export const del: APIRoute = async ({ params, redirect }) => { +export const DELETE: APIRoute = async ({ params, redirect }) => { if (!params.id) { return new Response("Cannot find friend", { status: 404, diff --git a/src/content/docs/en/guides/content-collections.mdx b/src/content/docs/en/guides/content-collections.mdx index f3f451906fae0..f77ddc2cf2269 100644 --- a/src/content/docs/en/guides/content-collections.mdx +++ b/src/content/docs/en/guides/content-collections.mdx @@ -395,6 +395,16 @@ const publishedBlogEntries = await getCollection('blog', ({ data }) => { }); ``` +You can also create draft pages that are available when running the dev server, but not built in production: + +```js +// Example: Filter out content entries with `draft: true` only when building for production +import { getCollection } from 'astro:content'; +const blogEntries = await getCollection('blog', ({ data }) => { + return import.meta.env.PROD ? data.draft !== true : true; +}); +``` + The filter argument also supports filtering by nested directories within a collection. Since the `id` includes the full nested path, you can filter by the start of each `id` to only return items from a specific nested directory: ```js @@ -706,7 +716,7 @@ This guide shows you how to convert an existing Astro project with Markdown file import rss from "@astrojs/rss"; import { getCollection } from "astro:content"; - export async function get() { + export async function GET() { const posts = await getCollection('posts'); return rss({ title: 'Astro Learner | Blog', diff --git a/src/content/docs/en/guides/deploy/netlify.mdx b/src/content/docs/en/guides/deploy/netlify.mdx index 6f73c8867d865..b97096558cbb2 100644 --- a/src/content/docs/en/guides/deploy/netlify.mdx +++ b/src/content/docs/en/guides/deploy/netlify.mdx @@ -121,7 +121,7 @@ You can also create a new site on Netlify and link up your Git repository by ins ### Set a Node.js Version -If you are using a legacy [build image](https://docs.netlify.com/configure-builds/get-started/#build-image-selection) (Xenial) on Netlify, make sure that your Node.js version is set. Astro requires `v16.12.0` or higher. +If you are using a legacy [build image](https://docs.netlify.com/configure-builds/get-started/#build-image-selection) (Xenial) on Netlify, make sure that your Node.js version is set. Astro requires `v18.14.1` or higher. You can [specify your Node.js version in Netlify](https://docs.netlify.com/configure-builds/manage-dependencies/#node-js-and-javascript) using: - a [`.nvmrc`](https://github.com/nvm-sh/nvm#nvmrc) file in your base directory. diff --git a/src/content/docs/en/guides/deploy/render.mdx b/src/content/docs/en/guides/deploy/render.mdx index 98f6112bc1a33..08079057533a6 100644 --- a/src/content/docs/en/guides/deploy/render.mdx +++ b/src/content/docs/en/guides/deploy/render.mdx @@ -15,5 +15,5 @@ You can deploy your Astro project to [Render](https://render.com/), a service to 4. Give your website a name, select the branch and specify the build command and publish directory - **build command:** `npm run build` - **publish directory:** `dist` - - **Environment variables (advanced)**: By default, Render uses Node.js 14.17.0, but Astro [requires a higher version](/en/install/auto/#prerequisites). Add an environment variable with a **Variable key** of `NODE_VERSION` and a **Value** of `16.12.0` or higher to tell Render to use a compatible Node.js version. Alternatively, add a [`.node-version`](https://render.com/docs/node-version) or [`.nvmrc`](https://render.com/docs/node-version) file to your project to specify a Node.js version. + - **Environment variables (advanced)**: By default, Render uses Node.js 14.17.0, but Astro [requires a higher version](/en/install/auto/#prerequisites). Add an environment variable with a **Variable key** of `NODE_VERSION` and a **Value** of `18.14.1` or higher to tell Render to use a compatible Node.js version. Alternatively, add a [`.node-version`](https://render.com/docs/node-version) or [`.nvmrc`](https://render.com/docs/node-version) file to your project to specify a Node.js version. 5. Click the **Create Static Site** button diff --git a/src/content/docs/en/guides/deploy/vercel.mdx b/src/content/docs/en/guides/deploy/vercel.mdx index 6d92580aed19e..faa838700e13f 100644 --- a/src/content/docs/en/guides/deploy/vercel.mdx +++ b/src/content/docs/en/guides/deploy/vercel.mdx @@ -85,4 +85,4 @@ You can use `vercel.json` to override the default behavior of Vercel and to conf ### Upgrading to Astro 2.0 -Astro v2.0 drops support for Node 14, so make sure your project is using **Node `16.12.0` or later**. You can [define the Node.js version](https://vercel.com/changelog/node-js-version-now-customizable-in-the-project-settings) used during the Build Step and Serverless Functions from the General page under Project Settings. +Astro v2.0 drops support for Node 14, so make sure your project is using **Node `18.14.1` or later**. You can [define the Node.js version](https://vercel.com/changelog/node-js-version-now-customizable-in-the-project-settings) used during the Build Step and Serverless Functions from the General page under Project Settings. diff --git a/src/content/docs/en/guides/integrations-guide.mdx b/src/content/docs/en/guides/integrations-guide.mdx index 2a512ca2dd279..b95b5f0fd4160 100644 --- a/src/content/docs/en/guides/integrations-guide.mdx +++ b/src/content/docs/en/guides/integrations-guide.mdx @@ -126,17 +126,17 @@ To remove an integration, first uninstall the integration from your project ```shell - npm uninstall @astrojs/image + npm uninstall @astrojs/react ``` ```shell - pnpm uninstall @astrojs/image + pnpm uninstall @astrojs/react ``` ```shell - yarn remove @astrojs/image + yarn remove @astrojs/react ``` @@ -146,11 +146,11 @@ Next, remove the integration from your `astro.config.*` file: ```js title="astro.config.mjs" del={3,7} import { defineConfig } from 'astro/config' -import image from "@astrojs/image"; +import react from "@astrojs/react"; export default defineConfig({ integrations: [ - image() + react() ] }) ``` diff --git a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx index a000c5203b6cb..9f2dc2e005b4f 100644 --- a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx @@ -65,23 +65,37 @@ export default defineConfig({ default `"advanced"` -Cloudflare Pages has 2 different modes for deploying functions, `advanced` mode which picks up the `_worker.js` in `dist`, or a directory mode where pages will compile the worker out of a functions folder in the project root. +Cloudflare Pages has 2 different modes for deploying functions, `advanced` mode which picks up the `_worker.js` in `dist`, or a directory mode where pages will compile the worker out of a functions folder in the project root. For most projects the adapter default of `advanced` will be sufficient; the `dist` folder will contain your compiled project. -For most projects the adapter default of `advanced` will be sufficient; the `dist` folder will contain your compiled project. Switching to directory mode allows you to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) or write custom code to enable logging. +#### `mode:directory` -In directory mode, the adapter will compile the client side part of your app the same way by default, but moves the worker script into a `functions` folder in the project root. In this case, the adapter will only ever place a `[[path]].js` in that folder, allowing you to add additional plugins and pages middleware which can be checked into version control. - -With the build configuration `split: true`, the adapter instead compiles a separate bundle for each page. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing `functions` files with identical names, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages. - -Note that this adapter does not support using [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro will bundle the [Astro middleware](/en/guides/middleware/) into each page. +Switching to directory mode allows you to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) or write custom code to enable logging. ```ts -// directory mode +// astro.config.mjs export default defineConfig({ adapter: cloudflare({ mode: 'directory' }), }); ``` +In `directory` mode, the adapter will compile the client-side part of your app the same way as in `advanced` mode by default, but moves the worker script into a `functions` folder in the project root. In this case, the adapter will only ever place a `[[path]].js` in that folder, allowing you to add additional plugins and pages middleware which can be checked into version control. + +To instead compile a separate bundle for each page, set the `functionPerPath` option in your Cloudflare adapter config. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing `functions` files with identical names, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages. + +```diff +import {defineConfig} from "astro/config"; +import cloudflare from '@astrojs/cloudflare'; + +export default defineConfig({ + adapter: cloudflare({ + mode: 'directory', ++ functionPerRoute: true + }) +}) +``` + +Note that this adapter does not support using [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro will bundle the [Astro middleware](/en/guides/middleware/) into each page. + ## Enabling Preview In order for preview to work you must install `wrangler` @@ -156,7 +170,7 @@ See Cloudflare's documentation for [working with environment variables](https:// ```js // pages/[id].json.js -export function get({ params }) { +export function GET({ params }) { // Access environment variables per request inside a function const serverUrl = import.meta.env.SERVER_URL; const result = await fetch(serverUrl + "/user/" + params.id); diff --git a/src/content/docs/en/guides/integrations-guide/markdoc.mdx b/src/content/docs/en/guides/integrations-guide/markdoc.mdx index 8eab45a82a823..0358456dfeb63 100644 --- a/src/content/docs/en/guides/integrations-guide/markdoc.mdx +++ b/src/content/docs/en/guides/integrations-guide/markdoc.mdx @@ -356,6 +356,36 @@ Now, you can call this function from any Markdoc content entry: 📚 [See the Markdoc documentation](https://markdoc.dev/docs/functions#creating-a-custom-function) for more on using variables or functions in your content. +### Markdoc Language Server + +If you are using VS Code, there is an official [Markdoc language extension](https://marketplace.visualstudio.com/items?itemName=Stripe.markdoc-language-support) that includes syntax highlighting and autocomplete for configured tags. [See the language server on GitHub](https://github.com/markdoc/language-server.git) for more information. + +To set up the extension, create a `markdoc.config.json` file into the project root with following content: + +```json +[ + { + "id": "my-site", + "path": "src/content", + "schema": { + "path": "markdoc.config.mjs", + "type": "esm", + "property": "default", + "watch": true + } + } +] +``` + +The `schema` property contains all information to configure the language server for Astro content collections. It accepts following properties: + +* `path`: The path to the configuration file. +* `type`: The type of module your configuration file uses (`esm` allows `import` syntax). +* `property`: The exported property name that contains the configuration object. +* `watch`: Tell the server to watch for changes in the configuration. + +The top-level `path` property tells the server where content is located. Since Markdoc is specific to content collections, you can use `src/content`. + ### Pass Markdoc variables You may need to pass [variables][markdoc-variables] to your content. This is useful when passing SSR parameters like A/B tests. diff --git a/src/content/docs/en/guides/integrations-guide/netlify.mdx b/src/content/docs/en/guides/integrations-guide/netlify.mdx index cac5f43d478d8..128bb3e32038d 100644 --- a/src/content/docs/en/guides/integrations-guide/netlify.mdx +++ b/src/content/docs/en/guides/integrations-guide/netlify.mdx @@ -69,28 +69,11 @@ If you prefer to install the adapter manually instead, complete the following tw }); ``` -### Edge Functions - -Netlify has two serverless platforms, [Netlify Functions](https://docs.netlify.com/functions/overview/) and [Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/). With Edge Functions your code is distributed closer to your users, lowering latency. - -To deploy with Edge Functions, use `netlify/edge-functions` in the Astro config file instead of `netlify/functions`. - -```js ins={3} -// astro.config.mjs -import { defineConfig } from 'astro/config'; -import netlify from '@astrojs/netlify/edge-functions'; - -export default defineConfig({ - output: 'server', - adapter: netlify(), -}); -``` - ### Run middleware in Edge Functions When deploying to Netlify Functions, you can choose to use an Edge Function to run your Astro middleware. -To enable this, set the `build.excludeMiddleware` Astro config option to `true`: +To enable this, set the `edgeMiddleware` config option to `true`: ```js ins={9} // astro.config.mjs @@ -99,10 +82,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - excludeMiddleware: true, - }, + adapter: netlify({ + edgeMiddleware: true, + }), }); ``` @@ -148,10 +130,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - split: true, - }, + adapter: netlify({ + functionPerRoute: true, + }), }); ``` @@ -276,7 +257,7 @@ We check for common mime types for audio, image, and video files. To include spe import fs from 'node:fs'; -export function get() { +export function GET() { const buffer = fs.readFileSync('../image.jpg'); // Return the buffer directly, @astrojs/netlify will base64 encode the body diff --git a/src/content/docs/en/guides/integrations-guide/node.mdx b/src/content/docs/en/guides/integrations-guide/node.mdx index 6390c8d9fbeee..4708c89af5163 100644 --- a/src/content/docs/en/guides/integrations-guide/node.mdx +++ b/src/content/docs/en/guides/integrations-guide/node.mdx @@ -174,7 +174,7 @@ For standalone mode the server handles file servering in addition to the page an You can override the host and port the standalone server runs on by passing them as environment variables at runtime: ```shell -HOST=0.0.0.0 PORT=3000 node ./dist/server/entry.mjs +HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjs ``` #### HTTPS diff --git a/src/content/docs/en/guides/integrations-guide/preact.mdx b/src/content/docs/en/guides/integrations-guide/preact.mdx index 4aa862623bcf9..3d02d9e0f22cf 100644 --- a/src/content/docs/en/guides/integrations-guide/preact.mdx +++ b/src/content/docs/en/guides/integrations-guide/preact.mdx @@ -128,6 +128,41 @@ Check out the [`pnpm` overrides](https://pnpm.io/package_json#pnpmoverrides) and Currently, the `compat` option only works for React libraries that export code as ESM. If an error happens during build-time, try adding the library to `vite.ssr.noExternal: ['the-react-library']` in your `astro.config.mjs` file. ::: +## Options + +### Combining multiple JSX frameworks + +When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed. + +Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths. + +We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required: + +```js +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // Enable many frameworks to support all different kinds of components. + // No `include` is needed if you are only using a single JSX framework! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + ## Examples * The [Astro Preact example](https://github.com/withastro/astro/tree/latest/examples/framework-preact) shows how to use an interactive Preact component in an Astro project. diff --git a/src/content/docs/en/guides/integrations-guide/react.mdx b/src/content/docs/en/guides/integrations-guide/react.mdx index 0fdf9257fbcfe..633f6b417dde0 100644 --- a/src/content/docs/en/guides/integrations-guide/react.mdx +++ b/src/content/docs/en/guides/integrations-guide/react.mdx @@ -84,6 +84,39 @@ To use your first React component in Astro, head to our [UI framework documentat ## Options +### Combining multiple JSX frameworks + +When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed. + +Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths. + +We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required: + +```js +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // Enable many frameworks to support all different kinds of components. + // No `include` is needed if you are only using a single JSX framework! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + ### Children parsing Children passed into a React component from an Astro component are parsed as plain strings, not React nodes. @@ -101,7 +134,7 @@ import ReactComponent from './ReactComponent'; ``` -If you are using a library that *expects* more than one child element element to be passed, for example so that it can slot certain elements in different places, you might find this to be a blocker. +If you are using a library that *expects* more than one child element to be passed, for example so that it can slot certain elements in different places, you might find this to be a blocker. You can set the experimental flag `experimentalReactChildren` to tell Astro to always pass children to React as React vnodes. There is some runtime cost to this, but it can help with compatibility. diff --git a/src/content/docs/en/guides/integrations-guide/solid-js.mdx b/src/content/docs/en/guides/integrations-guide/solid-js.mdx index 68c766632aea8..b4d9baf047a2a 100644 --- a/src/content/docs/en/guides/integrations-guide/solid-js.mdx +++ b/src/content/docs/en/guides/integrations-guide/solid-js.mdx @@ -82,6 +82,41 @@ To use your first SolidJS component in Astro, head to our [UI framework document * 💧 client-side hydration options, and * 🤝 opportunities to mix and nest frameworks together +## Options + +### Combining multiple JSX frameworks + +When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed. + +Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths. + +We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required: + +```js +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // Enable many frameworks to support all different kinds of components. + // No `include` is needed if you are only using a single JSX framework! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + ## Troubleshooting For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help! diff --git a/src/content/docs/en/guides/integrations-guide/vercel.mdx b/src/content/docs/en/guides/integrations-guide/vercel.mdx index 2e3c88f528f71..2bf9dc3d1e185 100644 --- a/src/content/docs/en/guides/integrations-guide/vercel.mdx +++ b/src/content/docs/en/guides/integrations-guide/vercel.mdx @@ -73,18 +73,12 @@ If you prefer to install the adapter manually instead, complete the following tw You can deploy to different targets: -* `edge`: SSR inside an [Edge function](https://vercel.com/docs/concepts/functions/edge-functions). * `serverless`: SSR inside a [Node.js function](https://vercel.com/docs/concepts/functions/serverless-functions). * `static`: generates a static website following Vercel's output formats, redirects, etc. -:::note -deploying to the Edge has [its limitations](https://vercel.com/docs/concepts/functions/edge-functions#known-limitations). An edge function can't be more than 1 MB in size and they don't support native Node.js APIs, among others. -::: - You can change where to target by changing the import: ```js -import vercel from '@astrojs/vercel/edge'; import vercel from '@astrojs/vercel/serverless'; import vercel from '@astrojs/vercel/static'; ``` @@ -107,7 +101,7 @@ To configure this adapter, pass an object to the `vercel()` function call in `as ### analytics **Type:** `boolean`
-**Available for:** Serverless, Edge, Static
+**Available for:** Serverless, Static
**Added in:** `@astrojs/vercel@3.1.0` You can enable [Vercel Analytics](https://vercel.com/analytics) (including Web Vitals and Audiences) by setting `analytics: true`. This will inject Vercel’s tracking scripts into all your pages. @@ -128,7 +122,7 @@ export default defineConfig({ ### imagesConfig **Type:** `VercelImageConfig`
-**Available for:** Edge, Serverless, Static +**Available for:** Serverless, Static **Added in:** `@astrojs/vercel@3.3.0` Configuration options for [Vercel's Image Optimization API](https://vercel.com/docs/concepts/image-optimization). See [Vercel's image configuration documentation](https://vercel.com/docs/build-output-api/v3/configuration#images) for a complete list of supported parameters. @@ -151,7 +145,7 @@ export default defineConfig({ ### imageService **Type:** `boolean`
-**Available for:** Edge, Serverless, Static +**Available for:** Serverless, Static **Added in:** `@astrojs/vercel@3.3.0` When enabled, an [Image Service](/en/reference/image-service-reference/) powered by the Vercel Image Optimization API will be automatically configured and used in production. In development, a built-in Squoosh-based service will be used instead. @@ -192,7 +186,7 @@ import astroLogo from '../assets/logo.png'; ### includeFiles **Type:** `string[]`
-**Available for:** Edge, Serverless +**Available for:** Serverless Use this property to force files to be bundled with your function. This is helpful when you notice missing files. @@ -209,10 +203,6 @@ export default defineConfig({ }); ``` -:::note -When building for the Edge, all the dependencies get bundled in a single file to save space. **No extra file will be bundled**. So, if you *need* some file inside the function, you have to specify it in `includeFiles`. -::: - ### excludeFiles **Type:** `string[]`
@@ -233,9 +223,11 @@ export default defineConfig({ }); ``` -### Per-page functions +### Function bundling configuration -The Vercel adapter builds to a single function by default. Astro 2.7 added support for splitting your build into separate entry points per page. If you use this configuration the Vercel adapter will generate a separate function for each page. This can help reduce the size of each function so they are only bundling code used on that page. +The Vercel adapter splits builds into a separate function per route by default. This helps reduce the size of each function, as it only bundles code used on that page. + +You can disable this and build to a single function by setting the `functionPerRoute` configuration option to `false`: ```js // astro.config.mjs @@ -244,10 +236,9 @@ import vercel from '@astrojs/vercel/serverless'; export default defineConfig({ output: 'server', - adapter: vercel(), - build: { - split: true, - }, + adapter: vercel({ + functionPerRoute: false, + }), }); ``` @@ -286,7 +277,7 @@ You can use Vercel Edge middleware to intercept a request and redirect before se The `@astrojs/vercel/serverless` adapter can automatically create the Vercel Edge middleware from an Astro middleware in your code base. -This is an opt-in feature, and the `build.excludeMiddleware` option needs to be set to `true`: +This is an opt-in feature, and the `edgeMiddleware` option needs to be set to `true`: ```js // astro.config.mjs @@ -294,10 +285,9 @@ import { defineConfig } from 'astro/config'; import vercel from '@astrojs/vercel'; export default defineConfig({ output: 'server', - adapter: vercel(), - build: { - excludeMiddleware: true, - }, + adapter: vercel({ + edgeMiddleware: true, + }), }); ``` diff --git a/src/content/docs/en/guides/markdown-content.mdx b/src/content/docs/en/guides/markdown-content.mdx index 9877dd1cd5738..76db95a487c68 100644 --- a/src/content/docs/en/guides/markdown-content.mdx +++ b/src/content/docs/en/guides/markdown-content.mdx @@ -60,60 +60,6 @@ It probably isn't styled much, but Markdown does support: 📚 Read more about Astro's [file-based routing](/en/core-concepts/routing/) or options for creating [dynamic routes](/en/core-concepts/routing/#dynamic-routes). -### Draft Pages - -`draft: true` is an optional frontmatter value that will mark an individual Markdown or MDX page or post as "unpublished." By default, this page will be: -- excluded from the site build (**no page will be built**) -- returned by [`Astro.glob()`](/en/reference/api-reference/#astroglob) (**visible in lists of posts**) - -```markdown {5} ---- -# src/pages/post/blog-post.md -layout: ../../layouts/BaseLayout.astro -title: My Blog Post -draft: true ---- - -This is my in-progress blog post. - -No page will be built for this post. - -To build and publish this post: - -- update the frontmatter to `draft: false` or -- remove the `draft` property entirely. - -But, this page _will_ be returned by any matching `Astro.glob()` request. -``` - -To exclude draft posts from being included in a post archive, or list of most recent posts, you can filter the results returned by `Astro.glob()`: - -```js -const posts = await Astro.glob('../pages/post/*.md'); -const nonDraftPosts = posts.filter((post) => !post.frontmatter.draft); -``` - -#### Enable building draft pages - -To enable building draft pages by default, update `astro.config.mjs` by adding `drafts: true` to `markdown` or to the `mdx` integration: - -```js title="astro.config.mjs" ins={5, 8} -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - markdown: { - drafts: true, - }, - integrations: [mdx({ - drafts: true, - })], -}); -``` - -:::tip -You can also pass the `--drafts` flag when running `astro build` to build draft pages! -::: - ## Markdown Features Astro provides some extra, built-in Markdown features available when using Markdown and MDX files. @@ -183,7 +129,7 @@ For example, to prevent `<` being interpreted as the beginning of an HTML elemen Adding the Astro [MDX integration](/en/guides/integrations-guide/mdx/) enhances your Markdown authoring with JSX variables, expressions and components. -It also adds extra features to standard MDX, including support for [Markdown-style frontmatter in MDX](https://mdxjs.com/guides/frontmatter/). This allows you to use most of Astro's built-in Markdown features like a [frontmatter `layout`](#frontmatter-layout) property and a setting for [draft pages](#draft-pages). +It also adds extra features to standard MDX, including support for [Markdown-style frontmatter in MDX](https://mdxjs.com/guides/frontmatter/). This allows you to use most of Astro's built-in Markdown features like a [frontmatter `layout`](#frontmatter-layout) property. `.mdx` files must be written in [MDX syntax](https://mdxjs.com/docs/what-is-mdx/#mdx-syntax) rather than Astro’s HTML-like syntax. diff --git a/src/content/docs/en/guides/middleware.mdx b/src/content/docs/en/guides/middleware.mdx index d7a6688a4c8b0..4657879ff0a8d 100644 --- a/src/content/docs/en/guides/middleware.mdx +++ b/src/content/docs/en/guides/middleware.mdx @@ -45,7 +45,7 @@ You can import and use the utility function `defineMiddleware()` to take advanta ```ts // src/middleware.ts -import { defineMiddleware } from "astro/middleware"; +import { defineMiddleware } from "astro:middleware"; // `context` and `next` are automatically typed export const onRequest = defineMiddleware((context, next) => { @@ -137,7 +137,7 @@ export const onRequest = async (context, next) => { Multiple middlewares can be joined in a specified order using [`sequence()`](#sequence): ```js title="src/middleware.js" -import { sequence } from "astro/middleware"; +import { sequence } from "astro:middleware"; async function validation(_, next) { console.log("validation request"); @@ -218,4 +218,4 @@ This function can be used by integrations/adapters to programmatically execute t ### `trySerializeLocals` -A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. \ No newline at end of file +A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. diff --git a/src/content/docs/en/guides/rss.mdx b/src/content/docs/en/guides/rss.mdx index ed5d221fc82fb..20915062a0dd8 100644 --- a/src/content/docs/en/guides/rss.mdx +++ b/src/content/docs/en/guides/rss.mdx @@ -47,7 +47,7 @@ The example file below `src/pages/rss.xml.js` will create an RSS feed at `site/r ```js title="src/pages/rss.xml.js" import rss from '@astrojs/rss'; -export function get(context) { +export function GET(context) { return rss({ // `` field in output xml title: 'Buzz’s Blog', @@ -81,7 +81,7 @@ To create an RSS feed of pages managed in [content collections](/en/guides/conte import rss from '@astrojs/rss'; import { getCollection } from 'astro:content'; -export async function get(context) { +export async function GET(context) { const blog = await getCollection('blog'); return rss({ title: 'Buzz’s Blog', @@ -128,7 +128,7 @@ This function assumes, but does not verify, that all necessary feed properties a ```js title="src/pages/rss.xml.js" "pagesGlobToRssItems" "await pagesGlobToRssItems(" import rss, { pagesGlobToRssItems } from '@astrojs/rss'; -export async function get(context) { +export async function GET(context) { return rss({ title: 'Buzz’s Blog', description: 'A humble Astronaut’s guide to the stars', @@ -166,7 +166,7 @@ import sanitizeHtml from 'sanitize-html'; import MarkdownIt from 'markdown-it'; const parser = new MarkdownIt(); -export async function get(context) { +export async function GET(context) { const blog = await getCollection('blog'); return rss({ title: 'Buzz’s Blog', @@ -188,7 +188,7 @@ When using glob imports with Markdown, you may use the `compiledContent()` helpe import rss from '@astrojs/rss'; import sanitizeHtml from 'sanitize-html'; -export function get(context) { +export function GET(context) { const postImportResult = import.meta.glob('../posts/**/*.md', { eager: true }); const posts = Object.values(postImportResult); return rss({ diff --git a/src/content/docs/en/guides/server-side-rendering.mdx b/src/content/docs/en/guides/server-side-rendering.mdx index 7b225bf73cb61..89a06dd874257 100644 --- a/src/content/docs/en/guides/server-side-rendering.mdx +++ b/src/content/docs/en/guides/server-side-rendering.mdx @@ -172,7 +172,7 @@ And for an endpoint: ```js title="src/pages/myendpoint.js" {1} export const prerender = true; -export async function get() { +export async function GET() { return { body: JSON.stringify({ message: `This is my static endpoint` }), }; @@ -186,7 +186,7 @@ For a mostly static site configured as `output: hybrid`, add `export const prere ```js title="src/pages/randomnumber.js" {1} export const prerender = false; -export async function get() { +export async function GET() { let number = Math.random(); return { body: JSON.stringify({ number, message: `Here's a random number: ${number}` }), diff --git a/src/content/docs/en/guides/styling.mdx b/src/content/docs/en/guides/styling.mdx index 129240181a1e8..19bc77b32f38b 100644 --- a/src/content/docs/en/guides/styling.mdx +++ b/src/content/docs/en/guides/styling.mdx @@ -41,11 +41,11 @@ This CSS: Compiles to this: ```astro <style> - h1:where(.astro-HHNQFKH6) { + h1[data-astro-cid-hhnqfkh6] { color: red; } - .text:where(.astro-HHNQFKH6) { + .text[data-astro-cid-hhnqfkh6] { color: blue; } </style> @@ -159,8 +159,7 @@ import MyComponent from "../components/MyComponent.astro" <MyComponent class="red">This will be red!</MyComponent> ``` -This pattern lets you style child components directly. Astro will pass the parent’s scoped class name (e.g. `astro-HHNQFKH6`) through the `class` prop automatically, including the child in its parent’s scope. - +This pattern lets you style child components directly. Astro will pass the parent’s scoped class name (e.g. `astro-hhnqfkh6`) through the `class` prop automatically, including the child in its parent’s scope. Note this pattern only works when your [`scopedStyleStrategy` option](/en/reference/configuration-reference/#scopedstylestrategy) is either `'where'` or `'class'`. :::note[Scoped classes from parent components] Because the `class` prop includes the child in its parent’s scope, it is possible for styles to cascade from parent to child. To avoid this having unintended side effects, ensure you use unique class names in the child component. ::: @@ -531,24 +530,36 @@ If you are using Tailwind, the [typography plugin](https://tailwindcss.com/docs/ ### Bundle control -When Astro builds your site for production deployment it combines your CSS into chunks. Each page on your site is its own chunk, and additionally, CSS that is shared between multiple pages is further split off into their own chunks for reuse. +When Astro builds your site for production deployment, it minifies and combines your CSS into chunks. Each page on your site gets its own chunk, and additionally, CSS that is shared between multiple pages is further split off into their own chunks for reuse. + +However, when you have several pages sharing styles, some shared chunks can become really small. If all of them were sent separately, it would lead to many stylesheets requests and affect site performance. Therefore, by default Astro will link only those in your HTML above 4kB in size as `<link rel="stylesheet">` tags, while inlining smaller ones into `<style type="text/css">`. This approach provides a balance between the number of additional requests and the volume of CSS that can be cached between pages. + +You can configure the size at which stylesheets will be linked externally (in bytes) using the `assetsInlineLimit` vite build option. Note that this option affects script and image inlining as well. + +```js +import { defineConfig } from 'astro/config'; -In each of your HTML files there will be `<link rel="stylesheet">` tags added, one for each of the chunks that the pages needs. +export default defineConfig({ + vite: { + build: { + assetsInlineLimit: 1024, + } + }; +}); +``` -Sites with a large number of pages and many different shared styles can lead to many stylesheet requests and affect site performance. You can configure the `inlineStylesheets` option to reduce the number of these requests by putting (minimized) stylesheets into a `<style>` tag rather than request them externally. +If you would rather all project styles remain external, you can configure the `inlineStylesheets` build option. ```js import { defineConfig } from 'astro/config'; export default defineConfig({ build: { - inlineStylesheets: 'auto' + inlineStylesheets: 'never' } }); ``` -The `'auto'` option will inline only the stylesheets that are below the `vite.build.assetsInlineLimit` threshold, reducing the number of requests for smaller sheets. Larger stylesheets, such as global ones used by all pages, will still be fetched externally and cached. This option provides a balance between the number of stylesheets loaded and the styles that can be cached between pages. - You can also set this option to `'always'` which will inline all stylesheets. ## Advanced diff --git a/src/content/docs/en/guides/troubleshooting.mdx b/src/content/docs/en/guides/troubleshooting.mdx index 1d80ed7c8edb6..8d51a7beec1f9 100644 --- a/src/content/docs/en/guides/troubleshooting.mdx +++ b/src/content/docs/en/guides/troubleshooting.mdx @@ -198,7 +198,7 @@ To help you debug your Astro components, Astro provides a built-in [`<Debug />`] ```astro {2,7} --- -import { Debug } from 'astro/components'; +import { Debug } from 'astro:components'; const sum = (a, b) => a + b; --- @@ -210,7 +210,7 @@ The Debug component supports a variety of syntax options for even more flexible ```astro {2,7-9} --- -import { Debug } from 'astro/components'; +import { Debug } from 'astro:components'; const sum = (a, b) => a + b; const answer = sum(2, 4); --- diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx new file mode 100644 index 0000000000000..fd3fba8213159 --- /dev/null +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -0,0 +1,640 @@ +--- +title: Upgrade to Astro v3 +description: How to upgrade your project to the latest version of Astro (v3.0). +i18nReady: true +--- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' +import FileTree from '~/components/FileTree.astro' + + +This guide will help you migrate from Astro v2 to Astro v3. + +Need to upgrade an older project to v2? See our [older migration guide](/en/guides/upgrade-to/v2/). + +## Upgrade Astro + +Update your project's version of Astro to the latest version using your package manager. If you're using Astro integrations, please also update those to the latest version. + +<PackageManagerTabs> + <Fragment slot="npm"> + ```shell + # Upgrade to Astro v3.x + npm install astro@latest + + # Example: upgrade React and Tailwind integrations + npm install @astrojs/react@latest @astrojs/tailwind@latest + ``` + </Fragment> + <Fragment slot="pnpm"> + ```shell + # Upgrade to Astro v3.x + pnpm install astro@latest + + # Example: upgrade React and Tailwind integrations + pnpm install @astrojs/react@latest @astrojs/tailwind@latest + ``` + </Fragment> + <Fragment slot="yarn"> + ```shell + # Upgrade to Astro v3.x + yarn add astro@latest + + # Example: upgrade React and Tailwind integrations + yarn add @astrojs/react@latest @astrojs/tailwind@latest + ``` + </Fragment> +</PackageManagerTabs> + +:::note[Need to continue?] +After upgrading Astro to the latest version, you may not need to make any changes to your project at all! + +But, if you notice errors or unexpected behavior, please check below for what has changed that might need updating in your project. +::: + +## Astro v3.0 Experimental Flags Removed + +Remove the following experimental flags from `astro.config.mjs`: + +```js del={5-8} +// astro.config.mjs +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + experimental: { + assets: true, + viewTransitions: true, + }, +}) +``` + +These features are now available by default: + +- View Transitions for animated page transitions and persistent islands. See [view transitions API breaking changes and upgrading advice](/en/guides/view-transitions/#upgrade-to-v30-from-v2x) if you were using this experimental flag. +- A new image services API `astro:assets` for using images in Astro, including a new `<Image />` component and `getImage()` function. Please read the detailed [image upgrade advice](/en/guides/images/#upgrade-to-v30-from-v2x) **whether or not you were using this experimental flag** to see how this might affect your project. + +Read more about these two exciting features and more in the 3.0 Blog post! + + + +## Astro v3.0 Breaking Changes + +Astro v3.0 includes some breaking changes, as well as the removal of some previously deprecated features. If your project doesn't work as expected after upgrading to v3.0, check this guide for an overview of all breaking changes and instructions on how to update your codebase. + +See [the changelog](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md) for full release notes. + +### Removed: Support for Node 16 + +Node 16 is scheduled to reach its End of Life in September 2023. + +Astro v3.0 drops Node 16 support entirely so that all Astro users can take advantage of Node's more modern features. + +#### What should I do? + + Check that both your development environment and your deployment environment are using **Node `18.14.1` or higher**. + +1. Check your local version of Node using: + + ```sh + node -v + ``` + + + +2. Check your [deployment environment's](/en/guides/deploy/) own documentation to verify that they support Node 18. + + You can specify Node `18.14.1` for your Astro project either in a dashboard configuration setting or a `.nvmrc` file. + +```bash title=".nvmrc" +18.14.1 +``` +### Removed: Support for TypeScript 4 + +In Astro v2.x, the `tsconfig.json` presets include support for both TypeScript 4.x and 5.x. + +Astro v3.0 updates the `tsconfig.json` presets to only support TypeScript 5.x. Astro now assumes that you use TypeScript 5.0 (March 2023), or that your editor includes it (e.g. VS Code 1.77). + +#### What should I do? + +If you have installed TypeScript locally, update to at least v5.0. + +```bash +npm install typescript@latest --save-dev +``` + +### Removed: `@astrojs/image` + +In Astro v2.x, Astro offered an official image integration that included Astro `<Image />` and `<Picture />` components. + +Astro v3.0 removes this integration from the codebase entirely. Astro's new solution for images is a built-in image services API: `astro:assets`. + +#### What should I do? + +Remove the `@astrojs/image` integration from your project. You will need to not only uninstall the integration but also update or remove any import statements and existing `<Image />` and `<Picture />` components. You might also need to configure a preferred default image processing service. + +You will find [complete, step-by-step instructions for removing the old image integration](/en/guides/images/#remove-astrojsimage) in our Images guide. + +Migrating to `astro:assets` will also bring some new image options and features that you may now wish to use. Please see the full [v3.0 Image Upgrade Advice](/en/guides/images/#upgrade-to-v30-from-v2x) for full details! + +```js del={3,7} +// astro.config.mjs +import { defineConfig } from 'astro/config'; +import image from '@astrojs/image'; + +export default defineConfig({ + integrations: [ + image(), + ] +}) +``` + +### Removed: `<Markdown />` component + +In Astro v1.x, Astro deprecated the `<Markdown />` component and moved it to an external package. + +Astro v3.0 completely removes the package `@astrojs/markdown-component`. Astro's `<Markdown />` component will no longer work in your project. + +#### What should I do? + +Remove all instances of the `@astrojs/markdown-component`. + +```astro del={2} title="src/components/MyAstroComponent.astro" +--- +import Markdown from '@astrojs/markdown-component'; +--- +``` + +To continue using a similar `<Markdown />` component in your code, consider using [community integrations](https://astro.build/integrations/) such as [`astro-remote`](https://github.com/natemoo-re/astro-remote). Be sure to update your `<Markdown />` component imports and attributes as necessary, according to the integration's own documentation. + +Otherwise, delete all references to importing Astro's `<Markdown />` component and the component itself in your `.astro` files. You will need to rewrite your content as HTML directly or [import Markdown](/en/guides/markdown-content/#importing-markdown) from a `.md` file. + +### Removed: deprecated 1.x APIs + +In Astro v1.x, Astro deprecated config options as well as script/style `global` and `hoist` attributes types. These were kept for backwards compatibility. + +Astro v3.0 removes these deprecated APIs entirely. They can no longer be used in your Astro project. + +#### What should I do? + +If you are continuing to use v1.x APIs, use the new APIs for each feature instead: + +- Deprecated config options: See [the 0.26 migration guide](/en/guides/upgrade-to/v1/#new-configuration-api) +- Deprecated script/style attribute types: See [the 0.26 migration guide](/en/guides/upgrade-to/v1/#new-default-script-behavior) + +### Removed: `image` from `astro:content` in content collections schema + +In Astro v2.x, the content collections API deprecated an `image` export from `astro:content` for use in your content collections schemas. + +Astro v3.0 removes this export entirely. + +#### What should I do? + +If you are using the deprecated `image()` from `astro:content`, remove it as this no longer exists. Validate images through [the `image` helper from `schema`](/en/guides/images/#update-content-collections-schemas) instead: + + ```ts title="astro.config.mjs" del={1} ins={2} "({ image })" +import { defineCollection, z, image } from "astro:content"; +import { defineCollection, z } from "astro:content"; + + defineCollection({ + schema: ({ image }) => + z.object({ + image: image(), + }), +}); +``` + +### Removed: pre-0.14 Shiki theme names + +In Astro v2.x, some Shiki theme names had been renamed, but the original names were kept for backwards compatibility. + +Astro v3.0 removes the original names in favor of the renamed theme names. + +#### What should I do? + +If your project uses any of the themes below, rename them to their updated name: + +- `material-darker` -> `material-theme-darker` +- `material-default` -> `material-theme` +- `material-lighter` -> `material-theme-lighter` +- `material-ocean` -> `material-theme-ocean` +- `material-palenight` -> `material-theme-palenight` + +### Removed: `class:list` features + +In Astro v2.x, the [`class:list` directive](/en/reference/directives-reference/#classlist) used a custom implementation inspired by [`clsx`](https://github.com/lukeed/clsx) with a few extra features like deduplication and `Set` support. + +Astro v3.0 now uses `clsx` directly for `class:list`, which does not support deduplication or `Set` values. + +#### What should I do? + +Replace any `Set` elements passed to the `class:list` directive with a plain `Array`. + +```astro title="src/components/MyAstroComponent.astro" del={4} ins={5} +<Component class:list={[ + 'a', + 'b', + new Set(['c', 'd']) + ['c', 'd'] +]} /> +``` + +### Removed: passing `class:list` as a prop + +In Astro v2.x, [`class:list` values](/en/reference/directives-reference/#classlist) were sent to components via [`Astro.props['class:list']`](/en/reference/api-reference/#astroprops). + +Astro v3.0 normalizes `class:list` values into a string before being sent to components via `Astro.props['class']` + +#### What should I do? + +Remove any code that expects to receive the `class:list` prop. + +```astro title="src/components/MyAstroComponent.astro" del={2,3,7} ins={4,8} "classList" "'class:list': classList" +--- +import { clsx } from 'clsx'; +const { class: className, 'class:list': classList } = Astro.props; +const { class: className } = Astro.props; +--- +<div + class:list={[className, classList]} + class:list={[className]} +/> +``` + +### Removed: kebab-case transform for camelCase CSS variables + +In Astro v2.x, camelCase [CSS variables](/en/guides/styling/#css-variables) passed to the `style` attribute were rendered as both camelCase (as written) and kebab-case (kept for backwards compatibility). + +Astro v3.0 removes the kebab-case transform for these camelCase CSS variable names, and only the original camelCase CSS variable is rendered. + +```astro "my-value" +--- +// src/components/MyAstroComponent.astro +const myValue = "red" +--- +<!-- input --> +<div style={{ "--myValue": myValue }}></div> + +<!-- output (Astro 2.x) --> +<div style="--my-value:var(--myValue);--myValue:red"></div> +<!-- output (Astro 3.0) --> +<div style="--myValue:red"></div> +``` + +#### What should I do? + +If you were relying on Astro to transform kebab-case in your styles, update your existing styles to camelCase to prevent missing styles. For example: + +```astro del={3} ins={4} title="src/components/MyAstroComponent.astro" +<style> + div { + color: var(--my-value); + color: var(--myValue); + } +</style> +``` + +### Removed: automatic flattening of `getStaticPaths()`'s return value + +In Astro v2.x, the return value of [`getStaticPaths()`](/en/reference/api-reference/#getstaticpaths) was automatically flattened to allow you to return an array of arrays without errors. + +Astro v3.0 removes automatic flattening of `getStaticPaths()`'s result. + +#### What should I do? + +If you're returning an array of arrays instead of an array of _objects_ (as is expected), `.flatMap` and `.flat` should now be used to ensure that you are returning a flat array. + +An [error message indicating that `getStaticPath()`'s return value must be an array of objects](/en/reference/errors/invalid-get-static-paths-entry/#what-went-wrong) will be provided if you need to update your code. + +### Moved: `astro check` now requires an external package + +In Astro v2.x, [`astro check`](/en/reference/cli-reference/#astro-check) was included in Astro by default, and its dependencies were bundled in Astro. This meant a larger package whether or not you ever used `astro check`. This also prevented you from having control over the version of TypeScript and the Astro Language Server to use. + + +Astro v3.0 moves the `astro check` command out of Astro core and now requires an external package `@astrojs/check`. Additionally, you must install `typescript` in your project to use the `astro check` command. + +#### What should I do? + +Run the `astro check` command after upgrading to Astro v3.0 and follow the prompts to install the required dependencies, or manually install `@astrojs/check` and `typescript` into your project. + +### Deprecated: `build.excludeMiddleware` and `build.split` + +In Astro v2.x, `build.excludeMiddleware` and `build.split` were used to change how specific files were emitted when using an adapter in SSR mode. + +Astro v3.0 replaces these build config options with new [SSR adapter configuration options](/en/guides/integrations-guide/#official-integrations) to perform the same tasks: `edgeMiddleware` and `functionPerRoute`. + +#### What should I do? + +Update the Astro config file to now use the new options **in the adapter configuration** directly. + +```js title="astro.config.mjs" del={5-7} ins={9} +import { defineConfig } from "astro/config"; +import vercel from "@astrojs/vercel/serverless"; + +export default defineConfig({ + build: { + excludeMiddleware: true + }, + adapter: vercel({ + edgeMiddleware: true + }), +}); +``` + +```js title="astro.config.mjs" del={5-7} ins={9} +import { defineConfig } from "astro/config"; +import netlify from "@astrojs/netlify/functions"; + +export default defineConfig({ + build: { + split: true + }, + adapter: netlify({ + functionPerRoute: true + }), +}); +``` + +### Deprecated: `markdown.drafts` + +In Astro v2.x, the `markdown.drafts` configuration allowed you to have draft pages that were available in when running the dev server, but not built in production. + +Astro v3.0 deprecates this feature in favor of the content collections method of handling draft pages by filtering manually instead, which gives more control over the feature. + +#### What should I do? + +To continue to mark some pages in your project as drafts, [migrate to content collections](/en/guides/content-collections/#migrating-from-file-based-routing) and [manually filter out pages](/en/guides/content-collections/#filtering-collection-queries) with the `draft: true` frontmatter property instead. + +### Deprecated: returning simple object in endpoints + +In Astro v2.x, endpoints could return a simple object, which would be converted to a JSON response. + +Astro v3.0 deprecates this behavior in favor of returning a `Response` object directly. + +#### What should I do? + +Update your endpoints to return a `Response` object directly. + +```ts title="endpoint.json.ts" del={2} ins={3} +export async function GET() { + return { body: { "title": "Bob's blog" }}; + return new Response(JSON.stringify({ "title": "Bob's blog" })); +} +``` + +If you really need to keep the previous format, you can use the `ResponseWithEncoding` object but will be deprecated in the future. + +```ts title="endpoint.json.ts" del={2} ins={3} +export async function GET() { + return { body: { "title": "Bob's blog" } }; + return new ResponseWithEncoding({ body: { "title": "Bob's blog" }}); +} +``` + +### Changed default: port `3000` + +In Astro v2.x, Astro ran on port `3000` by default. + +Astro v3.0 changes the [default port](/en/reference/cli-reference/#--port-number) to `4321`. 🚀 + +#### What should I do? + +Update any existing references to `localhost:3000`, for example in tests or in your `README`, to reflect the new port `localhost:4321`. + + +### Changed default: import.meta.env.BASE_URL `trailingSlash` + +In Astro v2.x, `import.meta.env.BASE_URL` appended your [`base`](/en/reference/configuration-reference/#base) setting with a [trailingSlash](/en/reference/configuration-reference/#trailingslash) by default. `trailingSlash: "ignore"` also appended a trailing slash. + +Astro v3.0 no longer appends `import.meta.env.BASE_URL` with a trailing slash by default, nor when `trailingSlash: "ignore"` is set. (The existing behavior of `base` in combination with `trailingSlash: "always"` or `trailingSlash: "never"` is unchanged.) + +#### What should I do? + +If your `base` already has a trailing slash, no change is needed. + +If your `base` does not have a trailing slash, add one if you wish to preserve the previous default (or `trailingSlash: "ignore"`) behavior: + +```js title="astro.config.mjs" del={4} ins={5} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + base: 'my-base', + base: 'my-base/', +}); +``` + +### Changed default: `compressHTML` + +In Astro v2.x, Astro only compressed your emitted HTML when [`compressHTML`](/en/reference/configuration-reference/#compresshtml) was explicitly set to `true`. The default value was `false`. + +Astro v3.0 now compresses emitted HTML by default. + +#### What should I do? + +You can now remove `compressHTML: true` from your configuration as this is the new default behavior. + +```js title="astro.config.mjs" del={4} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + compressHTML: true +}) +``` + +You must now set `compressHTML: false` to opt out of HTML compression. + +### Changed default: `scopedStyleStrategy` + +In Astro v2.x, the default value of [`scopedStyleStrategy`](/en/reference/configuration-reference/#scopedstylestrategy) was `"where"`. + +Astro v3.0 introduces a new, default value: `"attribute"`. By default, styles are now applied using `data-*` attributes. + +#### What should I do? + +To retain your project's current [style scoping](/en/guides/styling/#scoped-styles), update the configuration file to the previous default value: + + +```js title="astro.config.mjs" ins={4} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + scopedStyleStrategy: "where" +}) +``` + +### Changed default: `inlineStyleSheets` + +In Astro v2.x, all project stylesheets were sent as link tags by default. You could opt in to inlining them into `<style>` tags every time with `"always"`, or to inlining only stylesheets below a certain size with `"auto"` by setting the [`build.inlineStylesheets`](/en/reference/configuration-reference/#buildinlinestylesheets) configuration. The default setting was `"never"`. + +Astro v3.0 changes the default value of `inlineStylesheets` to `"auto"`. Stylesheets smaller than `ViteConfig.build.assetsInlineLimit` (default: 4kb) are inlined by default. Otherwise, project styles are sent in external stylesheets. + +#### What should I do? +If you want to keep your project's current behavior, set `build.inlineStylesheets` to the previous default, `"never"`: + + +```js title="astro.config.mjs" ins={4-6} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + build: { + inlineStylesheets: "never" + } +}) +``` + +### Changed default: image service + +In Astro v2.x, Squoosh was the [default image processing service](/en/guides/images/#default-image-service). + +Astro v3.0 now includes Sharp as the default image processing service and instead provides a configuration option to use Squoosh. + +#### What should I do? + +If you would prefer to continue to use Squoosh to transform your images, update your config with the following: + +```ts title="astro.config.mjs" ins={4-6} +import { defineConfig, squooshImageService } from "astro/config"; + +export default defineConfig({ + image: { + service: squooshImageService(), + } +}) +``` + +### Changed: HTTP request methods case + +In Astro v2.x, [HTTP request methods](/en/core-concepts/endpoints/#http-methods) were written using lowercase function names: `get`, `post`, `put`, `all`, and `del`. + +Astro v3.0 uses uppercase function names, including `DELETE` instead of `del`. + +#### What should I do? + +Rename all functions to their uppercase equivalent: + +- `get` to `GET` +- `post` to `POST` +- `put` to `PUT` +- `all` to `ALL` +- `del` to `DELETE` + +```js title="endpoint.ts" del={1} ins={2} +export function get() { +export function GET() { + return new Response(JSON.stringify({ "title": "Bob's blog" })); +} +``` + +### Changed: Multiple JSX framework configuration + +In Astro v2.x, you could use [multiple JSX framework integrations](/en/guides/integrations-guide/#official-integrations) (React, Solid, Preact) in the same project without needing to identify which files belonged to which framework. + +Astro v3.0 now requires you to specify which framework to use for your files with new `include` and `exclude` integration config options when you have multiple JSX framework integrations installed. This allows Astro to better support single-framework usage, as well as advanced features like React Fast Refresh. + +#### What should I do? + +If you are using multiple JSX frameworks in the same project, set `include` (and optionally `exclude`) to an array of files and/or folders. Wildcards may be used to include multiple file paths. + +We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required: + +```js ins={13,16,19} +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // Enable many frameworks to support all different kinds of components. + // No `include` is needed if you are only using a single framework! + integrations: [ + preact({ + include: ['**/preact/*'] + }), + react({ + include: ['**/react/*'] + }), + solid({ + include: ['**/solid/*'], + }), + ] +}); +``` + +### Changed: `Astro.cookies.get(key)` can return `undefined` + +In Astro v2.x, [`Astro.cookies.get(key)`](/en/reference/api-reference/#astrocookies) would always return an [`AstroCookie` object](/en/reference/api-reference/#astrocookie), even if the cookie did not exist. To check for its existence, you needed to use `Astro.cookies.has(key)`. + +Astro v3.0 returns `undefined` for `Astro.cookies.get(key)` if the cookie does not exist. + +#### What should I do? + +This change will not break any code that checks for the existence of the `Astro.cookie` object before using `Astro.cookies.get(key)`, but is now no longer required. + +You can safely remove any code that uses `has()` to check if the value of `Astro.cookies` is `undefined`: + +```js del={1-3} ins={5-7} +if (Astro.cookies.has(id)) { + const id = Astro.cookies.get(id)!; +} + +const id = Astro.cookies.get(id); +if (id) { +} +``` + +### Changed: running the Astro CLI programmatically + +In Astro v2.x, the `"astro"` package entrypoint exported and ran the Astro CLI directly. It is not recommended to run Astro this way in practice. + +Astro v3.0 removes the CLI from the entrypoint, and exports a new set of experimental JavaScript APIs, including `dev()`, `build()`, `preview()`, and `sync()`. + +#### What should I do? + +To [run the Astro CLI programatically](/en/reference/cli-reference/#advanced-apis-experimental), use the new experimental JavaScript APIs: + +```js +import { dev, build } from "astro"; + +// Start the Astro dev server +const devServer = await dev(); +await devServer.stop(); + +// Build your Astro project +await build(); +``` + + +### Changed: internal Astro API entry point export paths + +In Astro v2.x, you could import internal Astro APIs from `astro/internal/*` and `astro/runtime/server/*`. + +Astro v3.0 removes the two entry points in favor of the existing `astro/runtime/*` entrypoint. Additionally, a new `astro/compiler-runtime` export has been added for compiler-specific runtime code. + +#### What should I do? + +These are entry points for Astro's internal API and should not affect your project. But if you do use these entrypoints, update as shown below: + +```js del={1,4,10} ins={2,5,11} +import 'astro/internal/index.js'; +import 'astro/runtime/server/index.js'; + +import 'astro/server/index.js'; +import 'astro/runtime/server/index.js'; +``` + +```js ins={5} del={4} +import { transform } from '@astrojs/compiler'; + +const result = await transform(source, { + internalURL: 'astro/runtime/server/index.js', + internalURL: 'astro/compiler-runtime', + // ... +}); +``` + + + +## Known Issues + +There are currently no known issues. + diff --git a/src/content/docs/en/guides/view-transitions.mdx b/src/content/docs/en/guides/view-transitions.mdx index e70eb38d63f71..81193b5cc1b92 100644 --- a/src/content/docs/en/guides/view-transitions.mdx +++ b/src/content/docs/en/guides/view-transitions.mdx @@ -1,52 +1,56 @@ --- -title: View Transitions (Experimental) +title: View Transitions description: >- - How to enable experimental support for view transitions in your Astro site. + Enable seamless navigation between pages in Astro with view transitions. i18nReady: true --- import Since from '~/components/Since.astro' -Support for **opt-in, per-page, view transitions** in Astro projects can be enabled behind an experimental flag. View transitions update your page content without the browser's normal, full-page navigation refresh and provide seamless animations between pages. +Astro supports **opt-in, per-page, view transitions** with just a few lines of code. View transitions update your page content without the browser's normal, full-page navigation refresh and provide seamless animations between pages. -Astro provides a `<ViewTransitions />` routing component that can be added to a single page's `<head>` to control page transitions as you navigate away to another page. It provides a lightweight client-side router that intercepts navigation and allows you to customize the transition between pages. Add this component to a reusable `.astro` component, such as a common head or layout, for animated page transitions across your entire site (SPA mode). +Astro provides a `<ViewTransitions />` routing component that can be added to a single page's `<head>` to control page transitions as you navigate away to another page. It provides a lightweight client-side router that [intercepts navigation](#client-side-navigation-process) and allows you to customize the transition between pages. + +Add this component to a reusable `.astro` component, such as a common head or layout, for [animated page transitions across your entire site (SPA mode)](#full-site-view-transitions-spa-mode). Astro's view transitions support is powered by the new [View Transitions](https://developer.chrome.com/docs/web-platform/view-transitions/) browser API and also includes: -- A few [built-in animations](#built-in-animation-directives), such as `slide` and `fade`. +- A few [built-in animation options](#built-in-animation-directives), such as `fade`, `slide`, and `none`. - Support for both forwards and backwards navigation animations. - The ability to fully [customize all aspects of transition animation](#customizing-animations), and build your own animations. +- The option to [prevent client-side navigation for non-page links](#preventing-client-side-navigation). - [Control over fallback behavior](#fallback-control) for browsers that do not yet support the View Transition APIs. +- Automatic support for [`prefers-reduced-motion`](#prefers-reduced-motion). -:::caution -View transitions is an experimental feature enabled in Astro 2.9. The API is subject to change before it is marked as stable. -::: -## Enabling View Transitions in your Project +:::note +By default, every page will use regular, full-page, browser navigation. You must opt in to view transitions and can use them either on a per-page basis or site-wide. +::: -You can enable support for animated page transitions through the experimental `viewTransitions` flag in your Astro config: +## Adding View Transitions to a Page -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from 'astro/config'; +Opt in to using view transitions on individual pages by importing and adding the `<ViewTransitions />` routing component to `<head>` on every desired page. -export default defineConfig({ - experimental: { - viewTransitions: true - } -}); +```astro title="src/pages/index.astro" ins={2,7} +--- +import { ViewTransitions } from 'astro:transitions'; +--- +<html lang="en"> + <head> + <title>My Homepage + + + +

Welcome to my website!

+ + ``` -:::note -Enabling view transitions support does not automatically convert your entire site into a SPA (Single-page App). By default, every page will still use regular, full-page, browser navigation. - -Add page transitions in Astro with the `` routing component on a per-page basis, or site-wide. -::: - ## Full site view transitions (SPA mode) -Import and add the `` component to your common `` or shared layout component. Astro will create default page animations based on the similiarities between the old and new page, and will also provide fallback behavior for unsupported browsers. +Import and add the `` component to your common `` or shared layout component. Astro will create default page animations based on the similarities between the old and new page, and will also provide fallback behavior for unsupported browsers. -The example below shows adding view transitions site-wide by importing and adding this component to a `` Astro component: +The example below shows adding Astro's default page navigation animations site-wide, including the default fallback control option for non-supporting browsers, by importing and adding this component to a `` Astro component: ```astro title="components/CommonHead.astro" ins={2,12} --- @@ -63,7 +67,9 @@ import { ViewTransitions } from 'astro:transitions'; ``` -You can also add view transitions on a per-page basis. Import the `` component and place it directly inside of a page's ``. +No other configuration is necessary to enable Astro's default client-side navigation! + +Use [transition directives](#transition-directives) or [override default client-side navigation](#preventing-client-side-navigation) on individual elements for finer control. ## Transition Directives @@ -76,7 +82,7 @@ Use optional `transition:*` directives on page elements in your `.astro` compone - `transition:persist`: Allows you to override Astro's default replacing old elements for new ones and instead [persist components and HTML elements](#maintaining-state) when navigating to another page. -## Naming a transition +### Naming a transition In some cases, you may want or need to identify the corresponding view transition elements yourself. You can specify a name for a pair of elements using the `transition:name` directive. @@ -88,9 +94,9 @@ In some cases, you may want or need to identify the corresponding view transitio