From f399b687a44e5de782e269bafa86f9596a5fb309 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 10 Aug 2023 12:27:24 +0000 Subject: [PATCH 001/119] initial page --- src/content/docs/en/guides/upgrade-to/v3.mdx | 76 ++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/content/docs/en/guides/upgrade-to/v3.mdx 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..1b9d83b9537d6 --- /dev/null +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -0,0 +1,76 @@ +--- +title: Upgrade to Astro v3 +description: How to upgrade your project to the latest version of Astro. +i18nReady: false +--- +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. + + + + ```shell + # Upgrade to Astro v3.x + npm install astro@latest + + # Example: upgrade React and Tailwind integrations + npm install @astrojs/react@latest @astrojs/tailwind@latest + ``` + + + ```shell + # Upgrade to Astro v3.x + pnpm install astro@latest + + # Example: upgrade React and Tailwind integrations + pnpm install @astrojs/react@latest @astrojs/tailwind@latest + ``` + + + ```shell + # Upgrade to Astro v3.x + yarn add astro@latest + + # Example: upgrade React and Tailwind integrations + yarn add @astrojs/react@latest @astrojs/tailwind@latest + ``` + + + +## 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 later**. + +1. Check your local version of Node using: + + ```sh + node -v + ``` + + If your local development environment needs upgrading, [install Node](https://nodejs.org/en/download/). + + +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. + From 1f7eeba2b218a2894d29d3068f616c259fcf60f0 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 10 Aug 2023 13:00:44 +0000 Subject: [PATCH 002/119] a few entries to get us started --- src/content/docs/en/guides/upgrade-to/v3.mdx | 92 ++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 1b9d83b9537d6..2856d3888aa26 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -74,3 +74,95 @@ Astro v3.0 drops Node 16 support entirely, so that all Astro users can take adva You can specify Node `18.14.1` for your Astro project either in a dashboard configuration setting, or a `.nvmrc` file. +### Reserved: `src/assets/` + +Astro v3.0 now includes the new image services API for optimizing your image assets. This API reserves `src/assets/` as a special folder, with a built-in import alias: `~/assets` for referencing assets located here. + +#### What should I do? + +No change is required, and there will be no conflicts with an existing `src/assets/` folder. However, you will now have access to the built-in import alias and can choose to rename your asset imports within your files. This folder is not required, and your assets may continued to be located anywhere. + +### Changed: automatic flattening of `getStaticPaths()`'s return value + +:::note[Example needed] +Find an example of returning an array of an array +::: + +In Astro v2.x, we would magically flatten the result of `getStaticPaths()` automatically for the user, so if you returned an array of array, it would still work + +Astro v3.0 we changed this in favour of the user doing it themselves when they need to, in line with how we typically prefer for users to do explicit things. + +Removed automatic flattening of getStaticPaths result. .flatMap and .flat should now be used to ensure that you’re returning a flat array. + +#### What should I do? + +If you're returning an array of arrays instead of an array of object (as you should), please flatten it using .flat(), or if you're using a .map(), use .flatMap() instead + +A [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. + +### Changed: `build.excludeMiddleware` and `build.split` options have been moved to adapter config + +In Astro v2.x, `build.excludeMiddleware` and `build.split` could be used to change how specific files were emitted. + +Astro v3.0, these build config options have been replaced with new adapter configuruation options. + +#### What should I do? + +Update the config file to use the option **in the adapter**. + +```diff +import { defineConfig } from "astro/config"; +import vercel from "@astrojs/vercel/serverless"; + +export default defineConfig({ +- build: { +- excludeMiddleware: true +- }, + adapter: vercel({ ++ edgeMiddleware: true + }), +}); +``` + +```diff +import { defineConfig } from "astro/config"; +import vercel from "@astrojs/vercel/serverless"; + +export default defineConfig({ +- build: { +- split: true +- }, + adapter: vercel({ ++ functionPerRoute: true + }), +}); +``` + +```diff +import { defineConfig } from "astro/config"; +import netlify from "@astrojs/netlify/functions"; + +export default defineConfig({ +- build: { +- excludeMiddleware: true +- }, + adapter: netlify({ ++ edgeMiddleware: true + }), +}); +``` + +```diff +import { defineConfig } from "astro/config"; +import netlify from "@astrojs/netlify/functions"; + +export default defineConfig({ +- build: { +- split: true +- }, + adapter: netlify({ ++ functionPerRoute: true + }), +}); +``` + From ef1325ce62021c74552cea1de4eeb57d1b553fed Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 10 Aug 2023 13:23:33 +0000 Subject: [PATCH 003/119] added some more entries --- src/content/docs/en/guides/upgrade-to/v3.mdx | 98 +++++++++++++++----- 1 file changed, 76 insertions(+), 22 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 2856d3888aa26..066144f9a2b71 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -110,59 +110,113 @@ Astro v3.0, these build config options have been replaced with new adapter confi Update the config file to use the option **in the adapter**. -```diff +```astro title="astro.mjs.config" 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 - }), + build: { + excludeMiddleware: true + }, + adapter: vercel({ + edgeMiddleware: true + }), }); ``` -```diff +```astro title="astro.mjs.config" del={5-7} ins={9} import { defineConfig } from "astro/config"; import vercel from "@astrojs/vercel/serverless"; export default defineConfig({ -- build: { -- split: true -- }, + build: { + split: true + }, adapter: vercel({ -+ functionPerRoute: true + functionPerRoute: true }), }); ``` -```diff +```astro title="astro.mjs.config" del={5-7} ins={9} import { defineConfig } from "astro/config"; import netlify from "@astrojs/netlify/functions"; export default defineConfig({ -- build: { -- excludeMiddleware: true -- }, + build: { + excludeMiddleware: true + }, adapter: netlify({ -+ edgeMiddleware: true + edgeMiddleware: true }), }); ``` -```diff +```astro title="astro.mjs.config" del={5-7} ins={9} import { defineConfig } from "astro/config"; import netlify from "@astrojs/netlify/functions"; export default defineConfig({ -- build: { -- split: true -- }, + build: { + split: true + }, adapter: netlify({ -+ functionPerRoute: true + functionPerRoute: true }), }); ``` +### Changed: default image service to Sharp instead of Squoosh + +In Astro v2.x, Squoosh was the default image service. + +Astro v3.0, Sharp is now the default image service. + +#### What should I do? + +Sharp is now the default image service used for Astro. + +You no longer need to install the dependency locally in your project. + +Uninstall Sharp using your package manager, or by removing manually from your `package.json`. + +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: casing in function endpoints + +In Astro v2.x, endpoints were defined using lowercase function names: `get`, `post`, `put`, `all`, and `del`. + +Astro v3.0, uses uppercase function names. + +#### What should I do? + +Rename functions to uppercase equivalent: + +- `get` to `GET` +- `post` to `POST` +- `put` to `PUT` +- `all` to `ALL` +- `del` to `DELETE` + +:::note[Confirm with Ema] +Does `del` also become `DEL` and / or `DELETE`? + +Sarah prefers showing `DEL` only (for consistency) +::: + +```ts title="endpoint.ts" del={1} ins={2} +export function get() { +export function GET() { + return new Response(JSON.stringify({ "title": "Bob's blog" })); +} +``` From a6a08e621a6f095692100821d9bdb510c39bad29 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 10 Aug 2023 13:55:58 +0000 Subject: [PATCH 004/119] document Astro.cookies, compressHTML and default port --- src/content/docs/en/guides/upgrade-to/v3.mdx | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 066144f9a2b71..7142508a11064 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -220,3 +220,58 @@ export function GET() { return new Response(JSON.stringify({ "title": "Bob's blog" })); } ``` + +### Changed: Behaviour when `Astro.cookies.get(key)` doesn't exist + +In Astro v2.x, `Astro.cookies.get(key)` would always return a `AstroCookie` object, even if the cookie did not exist. To check for the existence you needed to use `Astro.cookies.has(key)`. + +Astro v3.0 `Astro.cookies.get(key)` will return `undefined` if the cookie does not exist. + +#### What should I do? + +This change will not break existing code that checks for the existance of the `Astro.cookie` object before using `Astro.cookies.get(key)`, but is now no longer required. You can safely remove this code. + +You can safely skip `has()` and check if the value is `undefined`: + +```ts +// before: +if (Astro.cookies.has(id)) { + const id = Astro.cookies.get(id)!; +} + +//after: +const id = Astro.cookies.get(id); +if (id) { + // TypeScript knows id is an AstroCookie +} +``` + +### Changed: the default value of `compressHTML` + +In Astro v2.x, Astro only compressed the emitted HTML by explicitly setting the configuration to `true`. + +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 now the default behavior. + +```ts 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 port used + +In Astro v2.x, Astro ran on port `3000` by default. + +Astro v3.0 changes the default port 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`. From 58c0d693f389aa52540429f7a18071fc8f322b07 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 15 Aug 2023 15:53:42 +0000 Subject: [PATCH 005/119] updates sidebar entry and adds more items to guide --- src/content/docs/en/guides/upgrade-to/v3.mdx | 55 ++++++++++++++++++++ src/i18n/en/nav.ts | 2 +- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 7142508a11064..eb6b6e5689b3a 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -275,3 +275,58 @@ Astro v3.0 changes the default port 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: TypeScript minimum version + +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? + +Update your TypeScript version to at least v5.0. + +```bash +npm install typescript@latest --save-dev +``` + +### Changed `astro check` is now an external package + +In Astro v2.x, `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` and 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. + +#### 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. + +### Added: simple asset support for Cloudflare, Deno, Vercel Edge and Netlify Edge + In Astro v2.x, using the assets feature in Cloudflare, Deno, Vercel Edge and Netlify Edge errors in runtime as the environments do not support Astro's builtin Squoosh and Sharp image optimization. + + Astro v3.0 allows these environments to work without errors, but does not perform any image transformation and processing. However, you would still get benefits, e.g. no Cumulative Layout Shift (CLS), enforced alt attribute, etc. + + What should I do? + If you previously avoided the assets feature due these constraints, you can now use them without issues. You can also use the no-op image service to explicitly opt-in to this behaviour: + + ``` + // astro.config.mjs + export default { + image: { + service: { + entrypoint: 'astro/assets/services/noop' + } + } + } + ``` + +In Astro v2.x, you would get an error log in development. When building a project, the build would fail. + +Astro V3 still displays the error log, but now you can build the project. + +When using an adapter that supports neither Squoosh or Sharp, Astro will now automatically use an image service that does not support processing, but still provides the other benefits of `astro:assets` such as enforcing `alt`, no CLS etc to users. Should be noted that it does no transformations or processing, but you still get all the other benefits (no CLS, alt enforced, etc). All of those benefits are part of the image service, if you make your own, you lose those benefits unless you make it yourself + + +## Known Issues + +There are currently no known issues. diff --git a/src/i18n/en/nav.ts b/src/i18n/en/nav.ts index 559771988165c..15ab74e540e29 100644 --- a/src/i18n/en/nav.ts +++ b/src/i18n/en/nav.ts @@ -12,7 +12,7 @@ export default [ { text: 'Getting Started', slug: 'getting-started', key: 'getting-started' }, { text: 'Installation', slug: 'install/auto', key: 'install' }, { text: 'Editor Setup', slug: 'editor-setup', key: 'editor-setup' }, - { text: 'Upgrade to v2', slug: 'guides/upgrade-to/v2', key: 'guides/upgrade-to/v2' }, + { text: 'Upgrade to v3', slug: 'guides/upgrade-to/v3', key: 'guides/upgrade-to/v3' }, { text: 'Core Concepts', header: true, type: 'learn', key: 'coreConcepts' }, { text: 'Why Astro', slug: 'concepts/why-astro', key: 'concepts/why-astro' }, From d8700434434cc7db107cd7feaf87cca6bee324de Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 15 Aug 2023 17:21:01 +0000 Subject: [PATCH 006/119] update sidebar in international versions --- src/i18n/es/nav.ts | 2 +- src/i18n/it/nav.ts | 2 +- src/i18n/ja/nav.ts | 2 +- src/i18n/ko/nav.ts | 2 +- src/i18n/pl/nav.ts | 2 +- src/i18n/pt-br/nav.ts | 2 +- src/i18n/ru/nav.ts | 2 +- src/i18n/zh-cn/nav.ts | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/i18n/es/nav.ts b/src/i18n/es/nav.ts index 3a8fa07b7dfda..dfa351d531712 100644 --- a/src/i18n/es/nav.ts +++ b/src/i18n/es/nav.ts @@ -3,7 +3,7 @@ export default [ { text: 'Cómo Empezar', slug: 'getting-started', key: 'getting-started' }, { text: 'Instalación', slug: 'install/auto', key: 'install' }, { text: 'Configuración del Editor', slug: 'editor-setup', key: 'editor-setup' }, - { text: 'Actualizar a v2', slug: 'guides/upgrade-to/v2', key: 'guides/upgrade-to/v2' }, + { text: 'Actualizar a v3', slug: 'guides/upgrade-to/v3', key: 'guides/upgrade-to/v3' }, { text: 'Conceptos Básicos', header: true, type: 'learn', key: 'coreConcepts' }, { text: 'Por qué Astro', slug: 'concepts/why-astro', key: 'concepts/why-astro' }, diff --git a/src/i18n/it/nav.ts b/src/i18n/it/nav.ts index ca7d48777af32..28c53cf8e7859 100644 --- a/src/i18n/it/nav.ts +++ b/src/i18n/it/nav.ts @@ -3,7 +3,7 @@ export default [ { text: 'Per Iniziare', slug: 'getting-started', key: 'getting-started' }, { text: 'Installazione', slug: 'install/auto', key: 'install' }, { text: 'Setup dell’Editor', slug: 'editor-setup', key: 'editor-setup' }, - { text: 'Aggiorna a v2', slug: 'guides/upgrade-to/v2', key: 'guides/upgrade-to/v2' }, + { text: 'Aggiorna a v3', slug: 'guides/upgrade-to/v3', key: 'guides/upgrade-to/v3' }, { text: 'Concetti Chiave', header: true, type: 'learn', key: 'coreConcepts' }, { text: 'Perché Astro', slug: 'concepts/why-astro', key: 'concepts/why-astro' }, diff --git a/src/i18n/ja/nav.ts b/src/i18n/ja/nav.ts index 1137b17cdbe09..af267c3671f93 100644 --- a/src/i18n/ja/nav.ts +++ b/src/i18n/ja/nav.ts @@ -6,7 +6,7 @@ export default NavDictionary({ 'getting-started': 'はじめに', install: 'インストール', 'editor-setup': 'エディタのセットアップ', - 'guides/upgrade-to/v2': 'v2へのアップグレード', + 'guides/upgrade-to/v3': 'v3へのアップグレード', // Core Concepts coreConcepts: 'コアコンセプト', diff --git a/src/i18n/ko/nav.ts b/src/i18n/ko/nav.ts index 0728a85b0d555..036a8fd4a57d0 100644 --- a/src/i18n/ko/nav.ts +++ b/src/i18n/ko/nav.ts @@ -7,7 +7,7 @@ export default NavDictionary({ coreConcepts: '핵심 개념', 'concepts/why-astro': '왜 Astro인가', 'editor-setup': '에디터 설정하기', - 'guides/upgrade-to/v2': 'v2로 업그레이드 하기', + 'guides/upgrade-to/v3': 'v3로 업그레이드 하기', basics: '기본', 'core-concepts/project-structure': '프로젝트 구조', 'guides/aliases': '별칭', diff --git a/src/i18n/pl/nav.ts b/src/i18n/pl/nav.ts index 4531bf69c2792..86772e32cf2bc 100644 --- a/src/i18n/pl/nav.ts +++ b/src/i18n/pl/nav.ts @@ -6,7 +6,7 @@ export default NavDictionary({ install: 'Instalacja', 'editor-setup': 'Konfiguracja edytora', 'guides/migrate-to-astro': 'Migracja do Astro', - 'guides/upgrade-to/v2': 'Aktualizacja do Astro 2.0', + 'guides/upgrade-to/v3': 'Aktualizacja do Astro 3.0', //migrate: 'Przewodnik migracji', tutorials: 'Samouczki', 'blog-tutorial': 'Zbuduj bloga', diff --git a/src/i18n/pt-br/nav.ts b/src/i18n/pt-br/nav.ts index 42ae83011bada..af4748507b33c 100644 --- a/src/i18n/pt-br/nav.ts +++ b/src/i18n/pt-br/nav.ts @@ -5,7 +5,7 @@ export default NavDictionary({ 'getting-started': 'Introdução', install: 'Instalação', 'editor-setup': 'Configuração do Editor', - 'guides/upgrade-to/v2': 'Atualize para a v2', + 'guides/upgrade-to/v3': 'Atualize para a v3', coreConcepts: 'Principais Conceitos', 'concepts/why-astro': 'Por que Astro?', 'concepts/islands': 'Ilhas Astro', diff --git a/src/i18n/ru/nav.ts b/src/i18n/ru/nav.ts index 5ccb91966f67f..17621f74d5ebc 100644 --- a/src/i18n/ru/nav.ts +++ b/src/i18n/ru/nav.ts @@ -51,7 +51,7 @@ export default NavDictionary({ 'guides/content-collections': 'Коллекции контента', 'guides/migrate-to-astro': 'Перейти на Astro', 'guides/testing': 'Тестирование', - 'guides/upgrade-to/v2': 'Обновление до v2', + 'guides/upgrade-to/v3': 'Обновление до v3', 'reference/error-reference': 'Справочник по ошибкам', tutorials: 'Обучение', examples: 'Рецепты', diff --git a/src/i18n/zh-cn/nav.ts b/src/i18n/zh-cn/nav.ts index 0a56350e8052d..9a1a3afd3c1a7 100644 --- a/src/i18n/zh-cn/nav.ts +++ b/src/i18n/zh-cn/nav.ts @@ -5,7 +5,7 @@ export default NavDictionary({ 'getting-started': '入门指南', install: '安装', 'editor-setup': '编辑器设置', - 'guides/upgrade-to/v2': '升级到 v2', + 'guides/upgrade-to/v3': '升级到 v3', coreConcepts: '核心理念', 'concepts/why-astro': '为什么选择Astro', From 95448d0658c6f41e0f7e86c16bc9929ab5ebd61f Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 15 Aug 2023 14:58:31 -0300 Subject: [PATCH 007/119] add more entries --- src/content/docs/en/guides/upgrade-to/v3.mdx | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index eb6b6e5689b3a..6585fd3bd60a2 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -327,6 +327,48 @@ Astro V3 still displays the error log, but now you can build the project. When using an adapter that supports neither Squoosh or Sharp, Astro will now automatically use an image service that does not support processing, but still provides the other benefits of `astro:assets` such as enforcing `alt`, no CLS etc to users. Should be noted that it does no transformations or processing, but you still get all the other benefits (no CLS, alt enforced, etc). All of those benefits are part of the image service, if you make your own, you lose those benefits unless you make it yourself +### Removed: `` component + +In Astro v2.x, Astro deprecated the `` component and moved it to an external package. + +Astro v3.0 comletely removes the package `@astrojs/markdown-component`, so Astro's `` component will no longer work in your project. + +#### What should I do? + +Uninstall the `@astrojs/markdown-component` package. To continue using a similar `` component in your code, consider using [community integrations](https://astro.build/integrations/) that provide a similar component like https://github.com/natemoo-re/astro-remote, and be sure to update your component imports and attributes as necessary according to the integration's own documentation. Otherwise, delete all references to importing Astro's `` 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 an `.md` file. + +### Removed: camelCase transformations + +In Astro 2.x, Astro automatically transformed camelCase CSS variable names passed to the `style` attribute of an HTML element. + +Astro 3.0 removes backwards-compatible kebab-case transform for these camelCase CSS variable names. + +#### What should I do? + +If you were relying on Astro to transform kebab-case in your styles, update your existing styles to use the camelCase version to prevent missing styles. For example: + +```astro +--- +const myValue = "red" +--- + +
+ +
+ +
+``` + +```diff + +``` + ## Known Issues There are currently no known issues. + From 61a35a55e1491abf78da9037228c8cd58939ac90 Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem Date: Wed, 16 Aug 2023 13:57:07 +0200 Subject: [PATCH 008/119] typo: fix `astro.mjs.config` to `astro.config.mjs` --- src/content/docs/en/guides/upgrade-to/v3.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 6585fd3bd60a2..b212fe18f0721 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -110,7 +110,7 @@ Astro v3.0, these build config options have been replaced with new adapter confi Update the config file to use the option **in the adapter**. -```astro title="astro.mjs.config" del={5-7} ins={9} +```astro title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import vercel from "@astrojs/vercel/serverless"; @@ -124,7 +124,7 @@ export default defineConfig({ }); ``` -```astro title="astro.mjs.config" del={5-7} ins={9} +```astro title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import vercel from "@astrojs/vercel/serverless"; @@ -138,7 +138,7 @@ export default defineConfig({ }); ``` -```astro title="astro.mjs.config" del={5-7} ins={9} +```astro title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import netlify from "@astrojs/netlify/functions"; @@ -152,7 +152,7 @@ export default defineConfig({ }); ``` -```astro title="astro.mjs.config" del={5-7} ins={9} +```astro title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import netlify from "@astrojs/netlify/functions"; From edfe8a9d4a0653ac8f92a4d87436b5749a93de17 Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem Date: Wed, 16 Aug 2023 14:23:29 +0200 Subject: [PATCH 009/119] refactor: endpoint methods to uppercase variants --- .../docs/en/core-concepts/endpoints.mdx | 30 +++++++++---------- .../en/guides/backend/google-firebase.mdx | 12 ++++---- .../docs/en/guides/content-collections.mdx | 2 +- src/content/docs/en/guides/rss.mdx | 10 +++---- .../docs/en/guides/server-side-rendering.mdx | 4 +-- .../docs/en/recipes/build-forms-api.mdx | 4 +-- .../docs/en/recipes/call-endpoints.mdx | 8 ++--- src/content/docs/en/recipes/captcha.mdx | 4 +-- .../docs/en/reference/api-reference.mdx | 16 +++++----- .../en/reference/image-service-reference.mdx | 2 +- .../docs/en/tutorial/5-astro-api/4.mdx | 2 +- 11 files changed, 47 insertions(+), 47 deletions(-) diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index 157444ea56bf6..f0894ef2677d6 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -17,7 +17,7 @@ Endpoints export a `get` function (optionally `async`) that receives a [context ```ts // Example: src/pages/builtwith.json.ts // Outputs: /builtwith.json -export async function get({params, request}) { +export async function GET({params, request}) { return { body: JSON.stringify({ name: 'Astro', @@ -30,7 +30,7 @@ export async function get({params, request}) { The return object can also have an `encoding` property. It can be any valid [`BufferEncoding`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/bdd02508ddb5eebcf701fdb8ffd6e84eabf47885/types/node/buffer.d.ts#L169) accepted by Node.js' `fs.writeFile` method. For example, to produce a binary png image: ```ts title="src/pages/astro-logo.png.ts" {6} -export async function get({ params, request }) { +export async function GET({ params, request }) { const response = await fetch("https://docs.astro.build/assets/full-logo-light.png"); const buffer = Buffer.from(await response.arrayBuffer()); return { @@ -45,7 +45,7 @@ You can also type your endpoint functions using the `APIRoute` type: ```ts import type { APIRoute } from 'astro'; -export const get: APIRoute = async ({ params, request }) => { +export const GET: APIRoute = async ({ params, request }) => { ... ``` @@ -58,7 +58,7 @@ import type { APIRoute } from 'astro'; const usernames = ["Sarah", "Chris", "Dan"] -export const get: APIRoute = ({ params, request }) => { +export const GET: APIRoute = ({ params, request }) => { const id = params.id; return { body: JSON.stringify({ @@ -84,7 +84,7 @@ All endpoints receive a `request` property, but in static mode, you only have ac ```ts title="src/pages/request-path.json.ts" import type { APIRoute } from 'astro'; -export const get: APIRoute = ({ params, request }) => { +export const GET: APIRoute = ({ params, request }) => { return { body: JSON.stringify({ path: new URL(request.url).pathname @@ -109,7 +109,7 @@ Server endpoints can access `params` without exporting `getStaticPaths`, and the ```js title="src/pages/[id].json.js" import { getProduct } from '../db'; -export async function get({ params }) { +export async function GET({ params }) { const id = params.id; const product = await getProduct(id); @@ -134,7 +134,7 @@ This will respond to any request that matches the dynamic route. For example, if In SSR mode, certain providers require the `Content-Type` header to return an image. In this case, use a `Response` object to specify a `headers` property. For example, to produce a binary `.png` image: ```ts title="src/pages/astro-logo.png.ts" -export async function get({ params, request }) { +export async function GET({ params, request }) { const response = await fetch("https://docs.astro.build/assets/full-logo-light.png"); const buffer = Buffer.from(await response.arrayBuffer()); return new Response(buffer, { @@ -144,16 +144,16 @@ export async function get({ params, request }) { ``` ### HTTP methods -In addition to the `get` function, you can export a function with the name of any [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). When a request comes in, Astro will check the method and call the corresponding function. +In addition to the `GET` function, you can export a function with the name of any [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). When a request comes in, Astro will check the method and call the corresponding function. -You can also export an `all` function to match any method that doesn't have a corresponding exported function. If there is a request with no matching method, it will redirect to your site's [404 page](/en/core-concepts/astro-pages/#custom-404-error-page). +You can also export an `ALL` function to match any method that doesn't have a corresponding exported function. If there is a request with no matching method, it will redirect to your site's [404 page](/en/core-concepts/astro-pages/#custom-404-error-page). :::note Since `delete` is a reserved word in JavaScript, export a `del` function to match the delete method. ::: ```ts title="src/pages/methods.json.ts" -export const get: APIRoute = ({ params, request }) => { +export const GET: APIRoute = ({ params, request }) => { return { body: JSON.stringify({ message: "This was a GET!" @@ -161,7 +161,7 @@ export const get: APIRoute = ({ params, request }) => { } }; -export const post: APIRoute = ({ request }) => { +export const POST: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: "This was a POST!" @@ -169,7 +169,7 @@ export const post: APIRoute = ({ request }) => { } } -export const del: APIRoute = ({ request }) => { +export const DEL: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: "This was a DELETE!" @@ -177,7 +177,7 @@ export const del: APIRoute = ({ request }) => { } } -export const all: APIRoute = ({ request }) => { +export const ALL: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: `This was a ${request.method}!` @@ -192,7 +192,7 @@ export const all: APIRoute = ({ request }) => { In SSR mode, the `request` property returns a fully usable [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object that refers to the current request. This allows you to accept data and check headers: ```ts title="src/pages/test-post.json.ts" -export const post: APIRoute = async ({ request }) => { +export const POST: APIRoute = async ({ request }) => { if (request.headers.get("Content-Type") === "application/json") { const body = await request.json(); const name = body.name; @@ -212,7 +212,7 @@ The endpoint context exports a `redirect()` utility similar to `Astro.redirect`: ```js title="src/pages/links/[id].js" {14} import { getLinkUrl } from '../db'; -export async function get({ params, redirect }) { +export async function GET({ params, redirect }) { const { id } = params; const link = await getLinkUrl(id); diff --git a/src/content/docs/en/guides/backend/google-firebase.mdx b/src/content/docs/en/guides/backend/google-firebase.mdx index 6f2da2c3c847e..0fbe235e267ac 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 */ @@ -586,7 +586,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 +628,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 +660,7 @@ export const post: APIRoute = async ({ params, redirect, request }) => { return redirect("/dashboard"); }; -export const del: APIRoute = async ({ params, redirect }) => { +export const DEL: 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..5997732577d05 100644 --- a/src/content/docs/en/guides/content-collections.mdx +++ b/src/content/docs/en/guides/content-collections.mdx @@ -706,7 +706,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/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/recipes/build-forms-api.mdx b/src/content/docs/en/recipes/build-forms-api.mdx index b2c5d02211e51..0edebd6c232f2 100644 --- a/src/content/docs/en/recipes/build-forms-api.mdx +++ b/src/content/docs/en/recipes/build-forms-api.mdx @@ -133,14 +133,14 @@ This recipe shows you how to send form data to an API endpoint and handle that d </UIFrameworkTabs> - 2. Create the `post` API endpoint that will receive the form data. Use `request.formData()` to process it. Be sure to validate the form values before you use them. + 2. Create the `POST` API endpoint that will receive the form data. Use `request.formData()` to process it. Be sure to validate the form values before you use them. This example sends a JSON object with a message back to the client. ```ts title="src/pages/api/feedback.ts" "request.formData()" "post" import type { APIRoute } from "astro"; - export const post: APIRoute = async ({ request }) => { + export const POST: APIRoute = async ({ request }) => { const data = await request.formData(); const name = data.get("name"); const email = data.get("email"); diff --git a/src/content/docs/en/recipes/call-endpoints.mdx b/src/content/docs/en/recipes/call-endpoints.mdx index 7492a747fb77e..cbd498869139a 100644 --- a/src/content/docs/en/recipes/call-endpoints.mdx +++ b/src/content/docs/en/recipes/call-endpoints.mdx @@ -18,7 +18,7 @@ Endpoints can be used to serve many kinds of data. This recipe calls a server en ```ts title="src/pages/api/hello.ts" import type { APIRoute } from 'astro' - export const get: APIRoute = () => { + export const GET: APIRoute = () => { return new Response( JSON.stringify({ greeting: 'Hello', @@ -27,13 +27,13 @@ Endpoints can be used to serve many kinds of data. This recipe calls a server en } ``` -2. On any Astro page, import the `get()` method from the endpoint. Call it with the [`Astro` global](/en/reference/api-reference/#astro-global) to provide the request context, and use the response on the page: +2. On any Astro page, import the `GET()` method from the endpoint. Call it with the [`Astro` global](/en/reference/api-reference/#astro-global) to provide the request context, and use the response on the page: ```astro title="src/pages/index.astro" --- - import { get } from './api/hello.ts' + import { GET } from './api/hello.ts' - let response = await get(Astro) + let response = await GET(Astro) const data = await response.json() --- diff --git a/src/content/docs/en/recipes/captcha.mdx b/src/content/docs/en/recipes/captcha.mdx index a684d3f1a7482..a587d3327ccfb 100644 --- a/src/content/docs/en/recipes/captcha.mdx +++ b/src/content/docs/en/recipes/captcha.mdx @@ -14,10 +14,10 @@ In this recipe, an API route is used to verify Google reCAPTCHA v3 without expos ## Recipe -1. Create a `post` endpoint that accepts recaptcha data, then verifies it with reCAPTCHA's API. Here, you can safely define secret values or read environment variables. +1. Create a `POST` endpoint that accepts recaptcha data, then verifies it with reCAPTCHA's API. Here, you can safely define secret values or read environment variables. ```js title="src/pages/recaptcha.js" - export async function post({ request }) { + export async function POST({ request }) { const data = await request.json(); const recaptchaURL = 'https://www.google.com/recaptcha/api/siteverify'; diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index bd6ec80ea9e77..2f57df4ceb56f 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -459,7 +459,7 @@ const orders = Array.from(Astro.locals.orders.entries()); ```ts title="endpoint.json.ts" import type { APIContext } from 'astro'; -export function get(context: APIContext) { +export function GET(context: APIContext) { // ... } ``` @@ -483,7 +483,7 @@ export function getStaticPaths() { ]; } -export function get({ params }: APIContext) { +export function GET({ params }: APIContext) { return { body: JSON.stringify({ id: params.id }) }; @@ -507,7 +507,7 @@ export function getStaticPaths() { ]; } -export function get({ props }: APIContext) { +export function GET({ props }: APIContext) { return { body: JSON.stringify({ author: props.author }), }; @@ -523,7 +523,7 @@ A standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) o ```ts import type { APIContext } from 'astro'; -export function get({ request }: APIContext) { +export function GET({ request }: APIContext) { return { body: `Hello ${request.url}` } @@ -551,7 +551,7 @@ Specifies the [IP address](https://en.wikipedia.org/wiki/IP_address) of the requ ```ts import type { APIContext } from 'astro'; -export function get({ clientAddress }: APIContext) { +export function GET({ clientAddress }: APIContext) { return { body: `Your IP address is: ${clientAddress}` } @@ -574,7 +574,7 @@ See also: [Astro.site](#astrosite) ```ts title="src/pages/site-info.json.ts" import type { APIContext } from 'astro'; -export function get({ generator, site }: APIContext) { +export function GET{ generator, site }: APIContext) { const body = JSON.stringify({ generator, site }); return new Response(body); } @@ -589,7 +589,7 @@ See also: [Astro.generator](#astrogenerator) ```ts import type { APIContext } from 'astro'; -export function get({ redirect }: APIContext) { +export function GET({ redirect }: APIContext) { return redirect('/login', 302); } ``` @@ -618,7 +618,7 @@ API endpoints can only read information from `context.locals`: ```ts title="src/pages/hello.ts" import type { APIContext } from 'astro'; -export function get({ locals }: APIContext) { +export function GET({ locals }: APIContext) { return { body: locals.title // "Default Title" } diff --git a/src/content/docs/en/reference/image-service-reference.mdx b/src/content/docs/en/reference/image-service-reference.mdx index b4eab6eb54852..cbfee55af0af8 100644 --- a/src/content/docs/en/reference/image-service-reference.mdx +++ b/src/content/docs/en/reference/image-service-reference.mdx @@ -133,7 +133,7 @@ If you implement your own endpoint as an Astro endpoint, you can use `getConfigu import type { APIRoute } from "astro"; import { getConfiguredImageService, imageServiceConfig } from 'astro:assets'; -export const get: APIRoute = async ({ request }) => { +export const GET: APIRoute = async ({ request }) => { const imageService = await getConfiguredImageService(); const imageTransform = imageService.parseURL(new URL(request.url), imageServiceConfig); 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 b964d81fd4052..ffea42e081416 100644 --- a/src/content/docs/en/tutorial/5-astro-api/4.mdx +++ b/src/content/docs/en/tutorial/5-astro-api/4.mdx @@ -78,7 +78,7 @@ Individuals can subscribe to your feed in a feed reader, and receive a notificat import rss, { pagesGlobToRssItems } from '@astrojs/rss'; - export async function get() { + export async function GET() { return rss({ title: 'Astro Learner | Blog', description: 'My journey learning Astro', From 2f4983c36a592eb1cec6d2192cc5507190c4ba53 Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem <hello@elian.codes> Date: Wed, 16 Aug 2023 14:43:07 +0200 Subject: [PATCH 010/119] chore: update DEL to DELETE --- src/content/docs/en/core-concepts/endpoints.mdx | 6 +----- src/content/docs/en/guides/backend/google-firebase.mdx | 2 +- src/content/docs/en/guides/upgrade-to/v3.mdx | 6 ------ 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index f0894ef2677d6..f03e7cb7352cf 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -148,10 +148,6 @@ In addition to the `GET` function, you can export a function with the name of an You can also export an `ALL` function to match any method that doesn't have a corresponding exported function. If there is a request with no matching method, it will redirect to your site's [404 page](/en/core-concepts/astro-pages/#custom-404-error-page). -:::note -Since `delete` is a reserved word in JavaScript, export a `del` function to match the delete method. -::: - ```ts title="src/pages/methods.json.ts" export const GET: APIRoute = ({ params, request }) => { return { @@ -169,7 +165,7 @@ export const POST: APIRoute = ({ request }) => { } } -export const DEL: APIRoute = ({ request }) => { +export const DELETE: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: "This was a DELETE!" diff --git a/src/content/docs/en/guides/backend/google-firebase.mdx b/src/content/docs/en/guides/backend/google-firebase.mdx index 0fbe235e267ac..5f18ea4bc89c7 100644 --- a/src/content/docs/en/guides/backend/google-firebase.mdx +++ b/src/content/docs/en/guides/backend/google-firebase.mdx @@ -660,7 +660,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/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index b212fe18f0721..515d89c1f9e17 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -208,12 +208,6 @@ Rename functions to uppercase equivalent: - `all` to `ALL` - `del` to `DELETE` -:::note[Confirm with Ema] -Does `del` also become `DEL` and / or `DELETE`? - -Sarah prefers showing `DEL` only (for consistency) -::: - ```ts title="endpoint.ts" del={1} ins={2} export function get() { export function GET() { From 09f569f31925f08d311354507814a9c31fdd51ec Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem <hello@elian.codes> Date: Thu, 17 Aug 2023 06:49:56 +0200 Subject: [PATCH 011/119] chore: remove `<Markdown />` component --- src/content/docs/en/reference/api-reference.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index 2f57df4ceb56f..5c82a9238c198 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -1046,10 +1046,6 @@ export default function () { 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';`. -### `<Markdown />` - -The Markdown component is no longer built into Astro. See how to [import Markdown into your Astro files](/en/guides/markdown-content/#importing-markdown) on our Markdown page. - ### `<Code />` ```astro 'theme="dark-plus"' /wrap\b/ /(inline) \/>/ From 6b0b53df00b3bc6e3cf7d446987fb6890bc50d5c Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Fri, 18 Aug 2023 21:16:54 +0000 Subject: [PATCH 012/119] all beta 0 and 1 placeholders entered --- src/content/docs/en/guides/upgrade-to/v3.mdx | 90 ++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 515d89c1f9e17..9c96267062d4d 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -362,6 +362,96 @@ const myValue = "red" </style> ``` +### Changed: default `scopedStyleStrategy` + +In Astro v2.x, the default value of `scopedStyleStrategy` was `"where"`. + +Astro v3.0, the default value is `"attribute"`. By default, styles are now applied using data-* attributes. + +#### What should I do? + +To retain your project's current style scoping, update the configuration file to the previous default value: + +```diff +export default defineConfig({ ++ scopedStyleStrategy: "where" +}) +``` + +### Changed: import.meta.env.BASE_URL default `trailingSlash` behaviour + +In Astro v2.x, `import.meta.env.BASE_URL`, which derives from `base` config, is always appended a trailingSlash by default or when `trailingSlash: "ignore"` is set. + +Astro v3.0 `import.meta.env.BASE_URL` is not appended with a trailingSlash by default or 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 to preserve the previous behaviour: + + ```diff + // astro.config.mjs + - base: 'my-base', + + base: 'my-base/', +``` + +### Changed: Multiple JSX framework configuration + +In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project and Astro without having to identify which files belonged to which framework. + +Astro v3.0, in order to better support single-framework usage, now requires that you specify which files are included in each integrations config. This change is only needed if using more than one of these frameworks; otherwise no configuration is needed. + +#### What should I do? + +When using multiple JSX frameworks in the same project, use the `include` and/or `exclude` configuration options to specify which files belong to which framework. We recommend having common framework components in the same folder; for ex. `components/react/` and `components/solid/`. This is not required but makes configuration easier: + +```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. + integrations: [ + preact({ include: ['**/preact/*'] }), + solid({ include: ['**/solid/*'] }), + react({ include: ['**/react/*'] }), + ], +}); +``` + +DUPLICATE FOR COMBINING + +Astro's JSX handling has been refactored with better support for each framework. + +Previously, Astro automatically scanned your components to determine which framework-specific transformations should be used. In practice, supporting advanced features like Fast Refresh with this approach proved difficult. + +Now, Astro determines which framework to use with `include` and `exclude` config options where you can specify files and folders on a per-framework basis. When using multiple JSX frameworks in the same project, users should manually control which files belong to each framework using the `include` and `exclude` options. + +```js +export default defineConfig({ + // The `include` config is only needed in projects that use multiple JSX frameworks; + // if only using one no extra config is needed. + integrations: [ + preact({ + include: ['**/preact/*'] + }), + react({ + include: ['**/react/*'] + }), + solid({ + include: ['**/solid/*'], + }), + ] +}); +``` + + + ## Known Issues There are currently no known issues. From 5c87a8e1a6138aae6905443ab1234492f8ae990c Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Fri, 18 Aug 2023 21:41:54 +0000 Subject: [PATCH 013/119] edit JSX entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 31 ++++---------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 9c96267062d4d..a2fd539f8181d 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -398,13 +398,15 @@ If your `base` already has a trailing slash, no change is needed. ### Changed: Multiple JSX framework configuration -In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project and Astro without having to identify which files belonged to which framework. +In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project and Astro without having to identify which files belonged to which framework. Astro automatically scanned your components to determine which framework-specific transformations should be used, but at a performance cost. -Astro v3.0, in order to better support single-framework usage, now requires that you specify which files are included in each integrations config. This change is only needed if using more than one of these frameworks; otherwise no configuration is needed. +Astro v3.0 determines which framework to use with `include` and `exclude` integration config options where you can specify files and folders on a per-framework basis. This allows Astro to better support single-framework usage, as well as advanced features like Fast Refresh. #### What should I do? -When using multiple JSX frameworks in the same project, use the `include` and/or `exclude` configuration options to specify which files belong to which framework. We recommend having common framework components in the same folder; for ex. `components/react/` and `components/solid/`. This is not required but makes configuration easier: +If you are using multiple JSX frameworks in the same project, use the `include` and/or `exclude` configuration options to specify which files belong to which framework. Provide 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 import { defineConfig } from 'astro/config'; @@ -416,26 +418,7 @@ import solid from '@astrojs/solid-js'; export default defineConfig({ // Enable many frameworks to support all different kinds of components. - integrations: [ - preact({ include: ['**/preact/*'] }), - solid({ include: ['**/solid/*'] }), - react({ include: ['**/react/*'] }), - ], -}); -``` - -DUPLICATE FOR COMBINING - -Astro's JSX handling has been refactored with better support for each framework. - -Previously, Astro automatically scanned your components to determine which framework-specific transformations should be used. In practice, supporting advanced features like Fast Refresh with this approach proved difficult. - -Now, Astro determines which framework to use with `include` and `exclude` config options where you can specify files and folders on a per-framework basis. When using multiple JSX frameworks in the same project, users should manually control which files belong to each framework using the `include` and `exclude` options. - -```js -export default defineConfig({ - // The `include` config is only needed in projects that use multiple JSX frameworks; - // if only using one no extra config is needed. + // No `include` is needed if you are only using a single framework! integrations: [ preact({ include: ['**/preact/*'] @@ -450,8 +433,6 @@ export default defineConfig({ }); ``` - - ## Known Issues There are currently no known issues. From 060607b6916c73b652c0d55d0102753e7d3997ea Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Fri, 18 Aug 2023 23:19:19 +0000 Subject: [PATCH 014/119] all placeholder entries in up to date! --- src/content/docs/en/guides/upgrade-to/v3.mdx | 142 ++++++++++++++++++- 1 file changed, 141 insertions(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index a2fd539f8181d..24f320e2bcce6 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -366,7 +366,7 @@ const myValue = "red" In Astro v2.x, the default value of `scopedStyleStrategy` was `"where"`. -Astro v3.0, the default value is `"attribute"`. By default, styles are now applied using data-* attributes. +Astro v3.0, the default value is `"attribute"`. By default, styles are now applied using `data-*` attributes. #### What should I do? @@ -433,6 +433,146 @@ export default defineConfig({ }); ``` +### Removed: `@astrojs/image` +In Astro v2.x, this package existed + +Astro v3.0, it does not anymore, replaced by `astro:assets` + +#### What should I do? + +Migrate to `astro:assets`. In `.astro` files this is really just a replace `@astrojs/image` by `astro:assets` in most cases, however if you used the Picture component, you'll need at this time to recreate it using the `getImage` APIs. + +### Removed: kebab-case transform for camelCase CSS variables + +In Astro v2.x, camelCase CSS variables passed to the `style` attribute were rendered as camelCase (original) and kebab-case (incorrect by kept for backwards compatibility). + +Astro v3.0 removes the kebab-case transform, and only the original camelCase CSS variable is rendered. + + ```astro + --- + const myValue = "red" + --- + <!-- input --> + <div style={{ "--myValue": myValue }}></div> + <!-- output (before) --> + <div style="--my-value:var(--myValue);--myValue:red"></div> + <!-- output (after) --> + <div style="--myValue:red"></div> + ``` + +#### What should I do? + +If you were relying on the kebab-case transform in your styles, make sure to use the camelCase version to prevent missing styles. For example: + + ```diff + <style> + div { + - color: var(--my-value); + + color: var(--myValue); + } + </style> + ``` +DUPE TO BE COMBINED + + Remove backwards-compatible kebab-case transform for camelCase CSS variable names passed to the `style` attribute. If you were relying on the kebab-case transform in your styles, make sure to use the camelCase version to prevent missing styles. For example: + +```astro +--- +const myValue = "red" +--- +<!-- input --> +<div style={{ "--myValue": myValue }}></div> +<!-- output (before) --> +<div style="--my-value:var(--myValue);--myValue:red"></div> +<!-- output (after) --> +<div style="--myValue:red"></div> +``` + +```diff +<style> + div { +- color: var(--my-value); ++ color: var(--myValue); + } +</style> +``` + +### Changed entrypoint export paths + +In Astro v2.x, you can import internal Astro APIs from `astro/internal/star` and `astro/runtime/server/star`. + +Astro v3.0 removes the two entrypoints in favour of the existing `astro/runtime/star` entrypoint. + +#### What should I do? + +These are entrypoints for Astro's internal API and should not affect your project, but if you do use these entrypoints, you can migrate like below: + + ```diff + - import 'astro/internal/index.js'; + + import 'astro/runtime/server/index.js'; + + - import 'astro/server/index.js'; + + import 'astro/runtime/server/index.js'; + ``` + +### Small stylesheets now get inlined by default +In Astro v2.x, all project stylesheets were sent lnd u could opt-in to inlining them by using the `build.inlineStylesheets` configuration. + +were sent as link tags by default and you could opt in to inlining them + +Astro v3.0 defaults `inlineStylesheets` to "auto", which means stylesheets smaller than 4kB get included in the initial response. + +#### What should I do? +Nothing, this change does not require any migration. To go back to the old behavior, configure `inlineStylesheets` to "never" + +```diff +export default defineConfig({ + build: { ++ inlineStylesheets: "never" + } +}) +``` + +### Changed implementation of `class:list` directive +In Astro v2.x, `class:list` used a custom implementation inspired by [`clsx`](https://github.com/lukeed/clsx) with a few extra features like deduplication and `Set` support. + +In Astro v3.0, `class:list` uses [`clsx`](https://github.com/lukeed/clsx) directly, 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`. + +```diff + <Component class:list={[ + 'a', + 'b', +- new Set(['c', 'd']) ++ ['c', 'd'] + ]} /> +``` + +### Changed behavior of `class:list` directive for components + +In Astro v2.x, `class:list` values were sent to components via `Astro.props['class:list']`. + +In Astro v3.0, `class:list` values are normalized 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. + +```diff +--- +- import { clsx } from 'clsx'; +- const { class: className, 'class:list': classList } = Astro.props; ++ const { class: className } = Astro.props; +--- +<div +- class:list={[className, classList]} ++ class={className} +/> +``` + ## Known Issues There are currently no known issues. From 33252d21a6e2ad8dd373d15764120e75bd5d81c6 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 00:10:35 +0000 Subject: [PATCH 015/119] added experimental flags to remove --- src/content/docs/en/guides/upgrade-to/v3.mdx | 63 +++++++++++++------- 1 file changed, 42 insertions(+), 21 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 24f320e2bcce6..f5f625760baa7 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -45,6 +45,31 @@ Update your project's version of Astro to the latest version using your package </Fragment> </PackageManagerTabs> +## 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](/en/guides/view-transitions/) for animated page transitions and persistent islands. +- [A new image services API `astro:assets`](/en/guides/images/) for optimizing and transforming images through the new `<Image />` component and `getImage()` function. Also unlocks [relative images in Markdown, MDX and Markdoc](/en/guides/images/#update-your-markdown-mdx-and-markdoc-files) using standard `![]()` syntax. + +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. @@ -74,13 +99,27 @@ Astro v3.0 drops Node 16 support entirely, so that all Astro users can take adva You can specify Node `18.14.1` for your Astro project either in a dashboard configuration setting, or a `.nvmrc` file. -### Reserved: `src/assets/` +### Removed: `@astrojs/image` +In Astro v2.x, this package existed -Astro v3.0 now includes the new image services API for optimizing your image assets. This API reserves `src/assets/` as a special folder, with a built-in import alias: `~/assets` for referencing assets located here. +Astro v3.0, it does not anymore, replaced by `astro:assets` #### What should I do? -No change is required, and there will be no conflicts with an existing `src/assets/` folder. However, you will now have access to the built-in import alias and can choose to rename your asset imports within your files. This folder is not required, and your assets may continued to be located anywhere. +Migrate to `astro:assets`. In `.astro` files this is really just a replace `@astrojs/image` by `astro:assets` in most cases, however if you used the Picture component, you'll need at this time to recreate it using the `getImage` APIs. + +Please see the full [v3 Image Upgrade Guide](/en/guides/images/#upgrade-to-v30-from-v2x) for details! + + +### Removed: `<Markdown />` component + +In Astro v2.x, Astro deprecated the `<Markdown />` component and moved it to an external package. + +Astro v3.0 comletely removes the package `@astrojs/markdown-component`, so Astro's `<Markdown />` component will no longer work in your project. + +#### What should I do? + +Uninstall the `@astrojs/markdown-component` package. To continue using a similar `<Markdown />` component in your code, consider using [community integrations](https://astro.build/integrations/) that provide a similar component like https://github.com/natemoo-re/astro-remote, and be sure to update your 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 an `.md` file. ### Changed: automatic flattening of `getStaticPaths()`'s return value @@ -321,16 +360,6 @@ Astro V3 still displays the error log, but now you can build the project. When using an adapter that supports neither Squoosh or Sharp, Astro will now automatically use an image service that does not support processing, but still provides the other benefits of `astro:assets` such as enforcing `alt`, no CLS etc to users. Should be noted that it does no transformations or processing, but you still get all the other benefits (no CLS, alt enforced, etc). All of those benefits are part of the image service, if you make your own, you lose those benefits unless you make it yourself -### Removed: `<Markdown />` component - -In Astro v2.x, Astro deprecated the `<Markdown />` component and moved it to an external package. - -Astro v3.0 comletely removes the package `@astrojs/markdown-component`, so Astro's `<Markdown />` component will no longer work in your project. - -#### What should I do? - -Uninstall the `@astrojs/markdown-component` package. To continue using a similar `<Markdown />` component in your code, consider using [community integrations](https://astro.build/integrations/) that provide a similar component like https://github.com/natemoo-re/astro-remote, and be sure to update your 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 an `.md` file. - ### Removed: camelCase transformations In Astro 2.x, Astro automatically transformed camelCase CSS variable names passed to the `style` attribute of an HTML element. @@ -433,14 +462,6 @@ export default defineConfig({ }); ``` -### Removed: `@astrojs/image` -In Astro v2.x, this package existed - -Astro v3.0, it does not anymore, replaced by `astro:assets` - -#### What should I do? - -Migrate to `astro:assets`. In `.astro` files this is really just a replace `@astrojs/image` by `astro:assets` in most cases, however if you used the Picture component, you'll need at this time to recreate it using the `getImage` APIs. ### Removed: kebab-case transform for camelCase CSS variables From adc2cc43b57e0697d098f430133aff01c7dd12fc Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 12:33:16 +0000 Subject: [PATCH 016/119] deleted the assets page since it won't be in new docs --- src/content/docs/en/guides/assets.mdx | 404 -------------------------- 1 file changed, 404 deletions(-) delete mode 100644 src/content/docs/en/guides/assets.mdx 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 `<Image />` 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} -/// <reference types="astro/client" /> -/// <reference types="astro/client-image" /> -``` - -### 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 `<img>` 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 `<img>` 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' ---- -<img src={rocket} width="250" height="250" alt="A rocketship in space." /> -<img src={rocket.src} width={rocket.width} height={rocket.height} alt="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 - -<!-- Local image stored at src/assets/stars.png --> -![A starry night sky.](../../assets/stars.png) -<img src="/_astro/stars.hash.webp" alt="A starry night sky."> - -<!-- Remote image on another server --> -![Astro logo](https://docs.astro.build/assets/logomark-light.png) -<img src="/_astro/logomark-light.hash.webp" width="25" alt="Astro logo"> - -<!-- Image stored at public/images/stars.png, will not be processed --> -![A starry night sky.](/images/stars.png) -<img src="/images/stars.png" alt="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 `<Image />` components. - - Change all `import` statements from `@astrojs/image/components` to `astro:assets` to use the new built-in `<Image />` 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"; - --- - - <Image - src={localImage} - width={300} - aspectRatio="16:9" - alt={localAlt} - /> - ``` - - -3. Remove any existing `<Picture />` components - - Currently, the built-in assets feature does not include a `<Picture />` component. - - Instead, you can use the HTML image attributes `srcset` and `sizes` or the `<picture>` 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 `<Image/>` 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) => ( - <div> - <Image src={post.data.cover} alt={post.data.coverAlt} /> - <h2> - <a href={"/blog/" + post.slug}>{post.data.title}</a> - </h2> - </div> - )) -} -``` - -### 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: - -- `<Image />` (available in `.astro` and `.mdx` files) -- `getImage()` (available in `.astro`, `.mdx`, `.ts`, `.js` on the server) - -:::caution -`<Image />` 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. -::: - -### `<Image />` (`astro:assets`) - -The `<Image />` component generates an `<img>` tag. - -This component can transform an image's dimensions, file type, and quality to produce an optimized image. The resulting `<img>` 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 `<Image />` component's `src` attribute. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; // Image is 1600x900 ---- - -<!-- `alt` is mandatory on the Image component --> -<Image src={myImage} alt="A description of my image." /> -``` - -```astro -<!-- Output --> -<!-- Image is optimized, proper attributes are enforced --> -<img - src="/_astro/my_image.hash.webp" - width="1600" - height="900" - decoding="async" - loading="lazy" - alt="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 `<Image />` 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 `<Image />` component accepts all properties accepted by the HTML `<img>` 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"; ---- - -<!-- `alt` is mandatory on the Image component --> -<Image src={myImage} alt="" class="my-class" /> -``` - -```astro -<!-- Output --> -<img - src="/_astro/my_image.hash.webp" - width="1600" - height="900" - decoding="async" - loading="lazy" - class="my-class" - alt="" -/> -``` - -### `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 `<Image />` 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'}) ---- - -<div style={`background-image: url(${optimizedBackground.src});`}></div> -``` - -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: - -<PackageManagerTabs> - <Fragment slot="npm"> - ```shell - npm install sharp - ``` - </Fragment> - <Fragment slot="pnpm"> - ```shell - pnpm install sharp - ``` - </Fragment> - <Fragment slot="yarn"> - ```shell - yarn add sharp - ``` - </Fragment> -</PackageManagerTabs> - -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(), - }, -}); -``` From 6a32051833327793c9ab43a00c1a8670371d47a0 Mon Sep 17 00:00:00 2001 From: Arsh <69170106+lilnasy@users.noreply.github.com> Date: Sat, 19 Aug 2023 18:20:19 +0530 Subject: [PATCH 017/119] Update CSS Bundle Control for 3.0 (#4253) Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> --- src/content/docs/en/guides/styling.mdx | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/content/docs/en/guides/styling.mdx b/src/content/docs/en/guides/styling.mdx index 129240181a1e8..85f325dcb42d4 100644 --- a/src/content/docs/en/guides/styling.mdx +++ b/src/content/docs/en/guides/styling.mdx @@ -531,24 +531,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. -In each of your HTML files there will be `<link rel="stylesheet">` tags added, one for each of the chunks that the pages needs. +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. -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. +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'; + +export default defineConfig({ + vite: { + build: { + assetsInlineLimit: 1024, + } + }; +}); +``` + +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 From 0f62bd24ea77f6a6ecfe323c16129fa5d7c6add2 Mon Sep 17 00:00:00 2001 From: Matthew Phillips <matthew@skypack.dev> Date: Sat, 19 Aug 2023 08:51:24 -0400 Subject: [PATCH 018/119] Use astro: namespace modules (#4239) --- src/content/docs/en/guides/middleware.mdx | 6 +++--- src/content/docs/en/guides/troubleshooting.mdx | 4 ++-- src/content/docs/en/reference/api-reference.mdx | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) 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/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/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index 5c82a9238c198..715858b0f2fe2 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -1044,13 +1044,13 @@ export default function () { ## 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';`. +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';`. ### `<Code />` ```astro 'theme="dark-plus"' /wrap\b/ /(inline) \/>/ --- -import { Code } from 'astro/components'; +import { Code } from 'astro:components'; --- <!-- Syntax highlight some JavaScript code. --> <Code code={`const foo = 'bar';`} lang="js" /> @@ -1112,7 +1112,7 @@ See the [list of languages supported by Prism](https://prismjs.com/#supported-la ```astro --- -import { Debug } from 'astro/components'; +import { Debug } from 'astro:components'; const serverObject = { a: 0, b: "string", From 58e22a8d4f2eadb118aa08853cbb0c17f7b8fef5 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa <my.burning@gmail.com> Date: Sat, 19 Aug 2023 14:04:23 +0100 Subject: [PATCH 019/119] feat: document astro features (#3924) Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> --- .../docs/en/reference/adapter-reference.mdx | 92 ++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/src/content/docs/en/reference/adapter-reference.mdx b/src/content/docs/en/reference/adapter-reference.mdx index f7ed4c3cdfc17..54974665714f2 100644 --- a/src/content/docs/en/reference/adapter-reference.mdx +++ b/src/content/docs/en/reference/adapter-reference.mdx @@ -2,6 +2,8 @@ title: Astro Adapter API i18nReady: true --- +import Since from '~/components/Since.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. @@ -26,7 +28,10 @@ export default function createIntegration() { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', - serverEntrypoint: '@matthewp/my-adapter/server.js' + serverEntrypoint: '@matthewp/my-adapter/server.js', + supportedAstroFeatures: { + staticOutput: 'stable' + } }); }, }, @@ -41,6 +46,40 @@ interface AstroAdapter { name: string; serverEntrypoint?: string; exports?: string[]; + supportedAstroFeatures: AstroFeatureMap; +} + +export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; + +export type AstroFeatureMap = { + /** + * The adapter is able to serve static pages + */ + staticOutput?: SupportsKind; + /** + * The adapter is able to serve pages that are static or rendered via server + */ + hybridOutput?: SupportsKind; + /** + * The adapter is able to serve SSR pages + */ + serverOutput?: SupportsKind; + /** + * The adapter can emit static assets + */ + assets?: AstroAssetsFeature; +}; + +export interface AstroAssetsFeature { + supportKind?: SupportsKind; + /** + * Whether or not this adapter deploys files in an environment that is compatible with the library `sharp` + */ + isSharpCompatible?: boolean; + /** + * Whether or not this adapter deploys files in an environment that is compatible with the library `squoosh` + */ + isSquooshCompatible?: boolean; } ``` @@ -49,6 +88,7 @@ The properties are: * __name__: A unique name for your adapter, used for logging. * __serverEntrypoint__: The entrypoint for server-side rendering. * __exports__: An array of named exports when used in conjunction with `createExports` (explained below). +* __supportedAstroFeatures__: A map of Astro built-in features. This allows Astro to determine which features an adapter is unable or unwilling to support so appropriate error messages can be provided. ### Server Entrypoint @@ -188,3 +228,53 @@ You can usually call `app.render(request)` without using `.match` because Astro ``` Once you [publish your adapter to npm](https://docs.npmjs.com/cli/v8/commands/npm-publish), running `astro add example` will install your package with any peer dependencies specified in your `package.json`. We will also instruct users to update their project config manually. + + +## Astro features + +<Since v="3.0.0" /> + +Astro features are a way for an adapter to tell Astro whether they are able to support a feature, and also the adapter's level of support. + +When using these properties, Astro will: +- run specific validation; +- emit contextual to the logs; + +These operations are run based on the features supported or not supported, their level of support, and the configuration that the user uses. + +The following configuration tells Astro that this adapter has experimental support for assets, but the adapter is not compatible with the built-in services Sharp and Squoosh: + +```js title="my-adapter.mjs" ins={9-15} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + supportedAstroFeatures: { + assets: { + supportKind: "experimental", + isSharpCompatible: false, + isSquooshCompatible: false + } + } + }); + }, + }, + }; +} +``` + +Astro will log a **warning** to the terminal: + +``` +[@matthewp/my-adapter] The feature is experimental and subject to issues or changes. +``` + +and an error if the service used for assets is not compatible with the adapter: + +``` +[@matthewp/my-adapter] The currently selected adapter `@matthewp/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build. +``` From 50a5f9efee534f0ab310aea8f40c4b0599f5a2a6 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa <my.burning@gmail.com> Date: Sat, 19 Aug 2023 14:18:37 +0100 Subject: [PATCH 020/119] feat: document logger for Astro integrations (#3817) Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> Co-authored-by: Reuben Tier <64310361+TheOtterlord@users.noreply.github.com> Co-authored-by: Chris Swithinbank <swithinbank@gmail.com> --- .../en/reference/integrations-reference.mdx | 86 +++++++++++++++++-- 1 file changed, 78 insertions(+), 8 deletions(-) diff --git a/src/content/docs/en/reference/integrations-reference.mdx b/src/content/docs/en/reference/integrations-reference.mdx index c1106a7eca069..42cc5d7a98d69 100644 --- a/src/content/docs/en/reference/integrations-reference.mdx +++ b/src/content/docs/en/reference/integrations-reference.mdx @@ -32,20 +32,26 @@ interface AstroIntegration { addClientDirective: (directive: ClientDirectiveConfig) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entryPoint: string }) => void; + logger: AstroIntegrationLogger; }) => void; - 'astro:config:done'?: (options: { config: AstroConfig }) => void | Promise<void>; - 'astro:server:setup'?: (options: { server: vite.ViteDevServer }) => void | Promise<void>; - 'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>; - 'astro:server:done'?: () => void | Promise<void>; - 'astro:build:start'?: () => void | Promise<void>; + 'astro:config:done'?: (options: { config: AstroConfig; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:server:done'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:build:start'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:setup'?: (options: { vite: ViteConfigWithSSR; pages: Map<string, PageBuildData>; target: 'client' | 'server'; + logger: AstroIntegrationLogger; }) => void | Promise<void>; - 'astro:build:generated'?: (options: { dir: URL }) => void | Promise<void>; - 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifestm, entryPoints: Map<RouteData, URL> }) => void | Promise<void>; - 'astro:build:done'?: (options: { dir: URL; routes: RouteData[] }) => void | Promise<void>; + 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:build:ssr'?: (options: { + manifest: SerializedSSRManifestm; + entryPoints: Map<RouteData, URL>; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:build:done'?: (options: { dir: URL; routes: RouteData[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; }; } ``` @@ -71,6 +77,7 @@ interface AstroIntegration { addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entryPoint: string }) => void; + logger: AstroIntegrationLogger; }) => void; ``` @@ -527,6 +534,69 @@ export default defineConfig({ This assumes your integration definition is 1) a `default` export and 2) a function. Ensure this is true before adding the `astro-integration` keyword! ::: +## `AstroIntegrationLogger` + +An instance of the Astro logger, useful to write logs. This logger uses the same [log level](/en/reference/cli-reference/#--verbose) +configured via CLI. + +**Methods available** to write to terminal: +- `logger.info("Messsage")`; +- `logger.warn("Messsage")`; +- `logger.error("Messsage")`; +- `logger.debug("Messsage")`; + +All the messages are prepended with a label that has the same value of the integration. + +```ts title="integration.ts" {8} +import type { AstroIntegration } from "astro"; +export function formatIntegration(): AstroIntegration { + return { + name: "astro-format", + hooks: { + "astro:build:done": (options, { logger }) => { + // do something + logger.info("Integration ready."); + } + } + } +} +``` + +The example above will log a message that includes the provided `info` message: + +```shell +[astro-format] Integration ready. +``` + +To log some messages with a different label, use the `.fork` method to specify an alternative to the default `name`: + +```ts title="integration.ts" ".fork" +import type { AstroIntegration } from "astro"; +export function formatIntegration(): AstroIntegration { + return { + name: "astro-format", + hooks: { + "astro:config:done": ({ logger }) => { + // do something + logger.info("Integration ready."); + }, + "astro:build:done": ({ logger }) => { + const buildLogger = logger.fork("astro-format/build"); + // do something + buildLogger.info("Build finished.") + } + } + } +} +``` + +The example above will produce logs with `[astro-format]` by default, and `[astro-format/build]` when specified: + +```shell +[astro-format] Integration ready. +[astro-format/build] Build finished. +``` + ## Integration Ordering All integrations are run in the order that they are configured. For instance, for the array `[react(), svelte()]` in a user's `astro.config.*`, `react` will run before `svelte`. From e76b7e66b0d4f4efea04bb54185c19eafc707625 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 14:08:11 +0000 Subject: [PATCH 021/119] removed Assets from sidebar since file was deleted --- src/i18n/en/nav.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/i18n/en/nav.ts b/src/i18n/en/nav.ts index 15ab74e540e29..242a27f371ea4 100644 --- a/src/i18n/en/nav.ts +++ b/src/i18n/en/nav.ts @@ -70,7 +70,6 @@ export default [ key: 'guides/client-side-scripts', }, { text: 'CSS & Styling', slug: 'guides/styling', key: 'guides/styling' }, - { text: 'Assets (Experimental)', slug: 'guides/assets', key: 'guides/assets' }, { text: 'Images', slug: 'guides/images', key: 'guides/images' }, { text: 'Fonts', slug: 'guides/fonts', key: 'guides/fonts' }, { text: 'Imports', slug: 'guides/imports', key: 'guides/imports' }, From 3210dcce116c3519446a29619887c2cf51ec10c0 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 14:35:52 +0000 Subject: [PATCH 022/119] updated image links to point to page we want them to visit --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index f5f625760baa7..adff407958dfe 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -64,7 +64,7 @@ export default defineConfig({ These features are now available by default: - [View Transitions](/en/guides/view-transitions/) for animated page transitions and persistent islands. -- [A new image services API `astro:assets`](/en/guides/images/) for optimizing and transforming images through the new `<Image />` component and `getImage()` function. Also unlocks [relative images in Markdown, MDX and Markdoc](/en/guides/images/#update-your-markdown-mdx-and-markdoc-files) using standard `![]()` syntax. +- A new image services API `astro:assets` for [using images in Astro](/en/guides/images/), including a new `<Image />` component and `getImage()` function. Read more about these two exciting features and more in the 3.0 Blog post! From fb9044b77050319aa64c90f6a7bc7a3a5cac91ad Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 14:55:56 +0000 Subject: [PATCH 023/119] edited removed astro image integration --- src/content/docs/en/guides/upgrade-to/v3.mdx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index adff407958dfe..ae9139a53bf43 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -100,15 +100,18 @@ Astro v3.0 drops Node 16 support entirely, so that all Astro users can take adva You can specify Node `18.14.1` for your Astro project either in a dashboard configuration setting, or a `.nvmrc` file. ### Removed: `@astrojs/image` -In Astro v2.x, this package existed -Astro v3.0, it does not anymore, replaced by `astro:assets` +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? -Migrate to `astro:assets`. In `.astro` files this is really just a replace `@astrojs/image` by `astro:assets` in most cases, however if you used the Picture component, you'll need at this time to recreate it using the `getImage` APIs. +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. -Please see the full [v3 Image Upgrade Guide](/en/guides/images/#upgrade-to-v30-from-v2x) for details! +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! ### Removed: `<Markdown />` component From d53181cd7b667da3f7a96d2f1c5f8660cd0cf640 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 15:10:00 +0000 Subject: [PATCH 024/119] edited removed markdown component --- src/content/docs/en/guides/upgrade-to/v3.mdx | 27 ++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index ae9139a53bf43..56b38455ba7c7 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -113,16 +113,39 @@ You will find [complete, step-by-step instructions for removing the old image in 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 v2.x, Astro deprecated the `<Markdown />` component and moved it to an external package. -Astro v3.0 comletely removes the package `@astrojs/markdown-component`, so Astro's `<Markdown />` component will no longer work in your project. +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? -Uninstall the `@astrojs/markdown-component` package. To continue using a similar `<Markdown />` component in your code, consider using [community integrations](https://astro.build/integrations/) that provide a similar component like https://github.com/natemoo-re/astro-remote, and be sure to update your 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 an `.md` file. +Remove all instances of the `@astrojs/markdown-component`. + +```astro del={3} +--- +// astro.config.mjs +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. ### Changed: automatic flattening of `getStaticPaths()`'s return value From 427f073fadc65e5e802fd7cf0773c244a7414aec Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 15:35:10 +0000 Subject: [PATCH 025/119] edited build config options moved to adapters --- src/content/docs/en/guides/upgrade-to/v3.mdx | 44 ++++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 56b38455ba7c7..6246faa38b27f 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -147,33 +147,15 @@ To continue using a similar `<Markdown />` component in your code, consider usin 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. -### Changed: automatic flattening of `getStaticPaths()`'s return value - -:::note[Example needed] -Find an example of returning an array of an array -::: - -In Astro v2.x, we would magically flatten the result of `getStaticPaths()` automatically for the user, so if you returned an array of array, it would still work - -Astro v3.0 we changed this in favour of the user doing it themselves when they need to, in line with how we typically prefer for users to do explicit things. - -Removed automatic flattening of getStaticPaths result. .flatMap and .flat should now be used to ensure that you’re returning a flat array. - -#### What should I do? - -If you're returning an array of arrays instead of an array of object (as you should), please flatten it using .flat(), or if you're using a .map(), use .flatMap() instead - -A [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. - -### Changed: `build.excludeMiddleware` and `build.split` options have been moved to adapter config +### Removed: `build.excludeMiddleware` and `build.split` -In Astro v2.x, `build.excludeMiddleware` and `build.split` could be used to change how specific files were emitted. +In Astro v2.x, `build.excludeMiddleware` and `build.split` could be used to change how specific files were emitted when using an adapter in SSR mode. -Astro v3.0, these build config options have been replaced with new adapter configuruation options. +Astro v3.0 replaces these build config options with new adapter configuration options **(CHECK ONLY Netlify, Vercel, and Cloudflare??)** to perform the same tasks: `edgeMiddleware` and `functionPerRoute`. #### What should I do? -Update the config file to use the option **in the adapter**. +Update the Astro config file to now use the new options **in the adapter configuration** directly. ```astro title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; @@ -231,6 +213,24 @@ export default defineConfig({ }); ``` +### Changed: automatic flattening of `getStaticPaths()`'s return value + +:::note[Example needed] +Find an example of returning an array of an array +::: + +In Astro v2.x, we would magically flatten the result of `getStaticPaths()` automatically for the user, so if you returned an array of array, it would still work + +Astro v3.0 we changed this in favour of the user doing it themselves when they need to, in line with how we typically prefer for users to do explicit things. + +Removed automatic flattening of getStaticPaths result. .flatMap and .flat should now be used to ensure that you’re returning a flat array. + +#### What should I do? + +If you're returning an array of arrays instead of an array of object (as you should), please flatten it using .flat(), or if you're using a .map(), use .flatMap() instead + +A [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. + ### Changed: default image service to Sharp instead of Squoosh In Astro v2.x, Squoosh was the default image service. From 2635170c428e4b25e24b56372940cafa42e1e3e6 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 17:43:15 +0000 Subject: [PATCH 026/119] remove extra build to adapter code samples --- src/content/docs/en/guides/upgrade-to/v3.mdx | 28 -------------------- 1 file changed, 28 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 6246faa38b27f..d34d4f1fb3909 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -171,34 +171,6 @@ export default defineConfig({ }); ``` -```astro title="astro.config.mjs" del={5-7} ins={9} -import { defineConfig } from "astro/config"; -import vercel from "@astrojs/vercel/serverless"; - -export default defineConfig({ - build: { - split: true - }, - adapter: vercel({ - functionPerRoute: true - }), -}); -``` - -```astro title="astro.config.mjs" del={5-7} ins={9} -import { defineConfig } from "astro/config"; -import netlify from "@astrojs/netlify/functions"; - -export default defineConfig({ - build: { - excludeMiddleware: true - }, - adapter: netlify({ - edgeMiddleware: true - }), -}); -``` - ```astro title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import netlify from "@astrojs/netlify/functions"; From 18c5a640bccfe7831794e30ecdcdb88c99a21ea8 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 17:48:24 +0000 Subject: [PATCH 027/119] updated typescript version entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 26 +++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index d34d4f1fb3909..1a9398427852b 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -99,6 +99,20 @@ Astro v3.0 drops Node 16 support entirely, so that all Astro users can take adva You can specify Node `18.14.1` for your Astro project either in a dashboard configuration setting, or a `.nvmrc` file. +### Removed: Support for TypeScript 4.x + +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. @@ -307,19 +321,7 @@ Astro v3.0 changes the default port to `4321`. Update any existing references to `localhost:3000`, for example in tests or in your `README` to reflect the new port `localhost:4321`. -### Changed: TypeScript minimum version - -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? - -Update your TypeScript version to at least v5.0. -```bash -npm install typescript@latest --save-dev -``` ### Changed `astro check` is now an external package From 864fc6d9466ed9eda7373d4c7f523ec500d7f909 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 18:10:25 +0000 Subject: [PATCH 028/119] kebab case, astro check entries done; end of REMOVEDs --- src/content/docs/en/guides/upgrade-to/v3.mdx | 145 ++++++------------- 1 file changed, 45 insertions(+), 100 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 1a9398427852b..afabf169e58b3 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -99,7 +99,7 @@ Astro v3.0 drops Node 16 support entirely, so that all Astro users can take adva You can specify Node `18.14.1` for your Astro project either in a dashboard configuration setting, or a `.nvmrc` file. -### Removed: Support for TypeScript 4.x +### Removed: Support for TypeScript 4 In Astro v2.x, the `tsconfig.json` presets include support for both TypeScript 4.x and 5.x. @@ -139,7 +139,6 @@ export default defineConfig({ }) ``` - ### Removed: `<Markdown />` component In Astro v2.x, Astro deprecated the `<Markdown />` component and moved it to an external package. @@ -199,6 +198,50 @@ export default defineConfig({ }); ``` +### Removed: kebab-case transform for camelCase CSS variables + +In Astro v2.x, camelCase CSS variables passed to the `style` attribute were rendered as both camelCase (as written) and kebab-case (kept for backwards compatibility). + +Astro 3.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: + +```diff +<style> + div { +- color: var(--my-value); ++ color: var(--myValue); + } +</style> +``` + +### Moved: `astro check` is now an external package + +In Astro v2.x, `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. + ### Changed: automatic flattening of `getStaticPaths()`'s return value :::note[Example needed] @@ -321,19 +364,6 @@ Astro v3.0 changes the default port to `4321`. Update any existing references to `localhost:3000`, for example in tests or in your `README` to reflect the new port `localhost:4321`. - - -### Changed `astro check` is now an external package - -In Astro v2.x, `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` and 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. - -#### 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. - ### Added: simple asset support for Cloudflare, Deno, Vercel Edge and Netlify Edge In Astro v2.x, using the assets feature in Cloudflare, Deno, Vercel Edge and Netlify Edge errors in runtime as the environments do not support Astro's builtin Squoosh and Sharp image optimization. @@ -360,36 +390,7 @@ Astro V3 still displays the error log, but now you can build the project. When using an adapter that supports neither Squoosh or Sharp, Astro will now automatically use an image service that does not support processing, but still provides the other benefits of `astro:assets` such as enforcing `alt`, no CLS etc to users. Should be noted that it does no transformations or processing, but you still get all the other benefits (no CLS, alt enforced, etc). All of those benefits are part of the image service, if you make your own, you lose those benefits unless you make it yourself -### Removed: camelCase transformations - -In Astro 2.x, Astro automatically transformed camelCase CSS variable names passed to the `style` attribute of an HTML element. - -Astro 3.0 removes backwards-compatible kebab-case transform for these camelCase CSS variable names. - -#### What should I do? - -If you were relying on Astro to transform kebab-case in your styles, update your existing styles to use the camelCase version to prevent missing styles. For example: - -```astro ---- -const myValue = "red" ---- -<!-- input --> -<div style={{ "--myValue": myValue }}></div> -<!-- output (before) --> -<div style="--my-value:var(--myValue);--myValue:red"></div> -<!-- output (after) --> -<div style="--myValue:red"></div> -``` -```diff -<style> - div { -- color: var(--my-value); -+ color: var(--myValue); - } -</style> -``` ### Changed: default `scopedStyleStrategy` @@ -462,62 +463,6 @@ export default defineConfig({ }); ``` - -### Removed: kebab-case transform for camelCase CSS variables - -In Astro v2.x, camelCase CSS variables passed to the `style` attribute were rendered as camelCase (original) and kebab-case (incorrect by kept for backwards compatibility). - -Astro v3.0 removes the kebab-case transform, and only the original camelCase CSS variable is rendered. - - ```astro - --- - const myValue = "red" - --- - <!-- input --> - <div style={{ "--myValue": myValue }}></div> - <!-- output (before) --> - <div style="--my-value:var(--myValue);--myValue:red"></div> - <!-- output (after) --> - <div style="--myValue:red"></div> - ``` - -#### What should I do? - -If you were relying on the kebab-case transform in your styles, make sure to use the camelCase version to prevent missing styles. For example: - - ```diff - <style> - div { - - color: var(--my-value); - + color: var(--myValue); - } - </style> - ``` -DUPE TO BE COMBINED - - Remove backwards-compatible kebab-case transform for camelCase CSS variable names passed to the `style` attribute. If you were relying on the kebab-case transform in your styles, make sure to use the camelCase version to prevent missing styles. For example: - -```astro ---- -const myValue = "red" ---- -<!-- input --> -<div style={{ "--myValue": myValue }}></div> -<!-- output (before) --> -<div style="--my-value:var(--myValue);--myValue:red"></div> -<!-- output (after) --> -<div style="--myValue:red"></div> -``` - -```diff -<style> - div { -- color: var(--my-value); -+ color: var(--myValue); - } -</style> -``` - ### Changed entrypoint export paths In Astro v2.x, you can import internal Astro APIs from `astro/internal/star` and `astro/runtime/server/star`. From 747a91cfa0e49007ffcbca21af7e5cede4f632e6 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 18:22:14 +0000 Subject: [PATCH 029/119] tralingslash default behavior entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 37 +++++++++++--------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index afabf169e58b3..cbb721bfac99a 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -242,6 +242,27 @@ Astro v3.0 moves the `astro check` command out of Astro core and now requires an 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. +### Changed default: import.meta.env.BASE_URL `trailingSlash` behaviour + +In Astro v2.x, `import.meta.env.BASE_URL` appended your `base` setting with a trailing slash by default. `trailingSlash: "ignore"`also appended a trailing slash. + +Astro v3.0 `import.meta.env.BASE_URL` is not appended 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"`) behaviour: + +```astro title="astro.config.mjs" del={4} ins={5} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + base: 'my-base', + base: 'my-base/', +}); +``` + ### Changed: automatic flattening of `getStaticPaths()`'s return value :::note[Example needed] @@ -408,23 +429,7 @@ export default defineConfig({ }) ``` -### Changed: import.meta.env.BASE_URL default `trailingSlash` behaviour - -In Astro v2.x, `import.meta.env.BASE_URL`, which derives from `base` config, is always appended a trailingSlash by default or when `trailingSlash: "ignore"` is set. - -Astro v3.0 `import.meta.env.BASE_URL` is not appended with a trailingSlash by default or 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 to preserve the previous behaviour: - ```diff - // astro.config.mjs - - base: 'my-base', - + base: 'my-base/', -``` ### Changed: Multiple JSX framework configuration From 7cb56ee43e875941645e22db1b42b09740ce79ac Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 18:27:52 +0000 Subject: [PATCH 030/119] htmlcompress entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 42 ++++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index cbb721bfac99a..bede8068dad5f 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -242,7 +242,7 @@ Astro v3.0 moves the `astro check` command out of Astro core and now requires an 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. -### Changed default: import.meta.env.BASE_URL `trailingSlash` behaviour +### Changed default: import.meta.env.BASE_URL `trailingSlash` In Astro v2.x, `import.meta.env.BASE_URL` appended your `base` setting with a trailing slash by default. `trailingSlash: "ignore"`also appended a trailing slash. @@ -263,6 +263,26 @@ export default defineConfig({ }); ``` +### Changed default: `compressHTML` + +In Astro v2.x, Astro only compressed your emitted HTML when `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. + +```ts 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: automatic flattening of `getStaticPaths()`'s return value :::note[Example needed] @@ -355,26 +375,6 @@ if (id) { } ``` -### Changed: the default value of `compressHTML` - -In Astro v2.x, Astro only compressed the emitted HTML by explicitly setting the configuration to `true`. - -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 now the default behavior. - -```ts 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 port used In Astro v2.x, Astro ran on port `3000` by default. From 68f73163403a005945812e6ace208826fe21acbd Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 18:43:29 +0000 Subject: [PATCH 031/119] scopedStyleStrategy and added links up to here --- src/content/docs/en/guides/upgrade-to/v3.mdx | 50 ++++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index bede8068dad5f..e58c02ad77b98 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -164,7 +164,7 @@ Otherwise, delete all references to importing Astro's `<Markdown />` component a In Astro v2.x, `build.excludeMiddleware` and `build.split` could be 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 adapter configuration options **(CHECK ONLY Netlify, Vercel, and Cloudflare??)** to perform the same tasks: `edgeMiddleware` and `functionPerRoute`. +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? @@ -233,7 +233,7 @@ If you were relying on Astro to transform kebab-case in your styles, update your ### Moved: `astro check` is now an external package -In Astro v2.x, `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. +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. @@ -244,9 +244,9 @@ Run the `astro check` command after upgrading to Astro v3.0 and follow the promp ### Changed default: import.meta.env.BASE_URL `trailingSlash` -In Astro v2.x, `import.meta.env.BASE_URL` appended your `base` setting with a trailing slash by default. `trailingSlash: "ignore"`also appended a trailing slash. +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 `import.meta.env.BASE_URL` is not appended 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. +Astro v3.0 does not appended `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? @@ -265,7 +265,7 @@ export default defineConfig({ ### Changed default: `compressHTML` -In Astro v2.x, Astro only compressed your emitted HTML when `compressHTML` was explicitly set to `true`. The default value was `false`. +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. @@ -283,6 +283,26 @@ export default defineConfig({ 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, update the configuration file to the previous default value: + + +```ts title="astro.config.mjs" ins={4} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + scopedStyleStrategy: "where" +}) +``` + + ### Changed: automatic flattening of `getStaticPaths()`'s return value :::note[Example needed] @@ -411,26 +431,6 @@ Astro V3 still displays the error log, but now you can build the project. When using an adapter that supports neither Squoosh or Sharp, Astro will now automatically use an image service that does not support processing, but still provides the other benefits of `astro:assets` such as enforcing `alt`, no CLS etc to users. Should be noted that it does no transformations or processing, but you still get all the other benefits (no CLS, alt enforced, etc). All of those benefits are part of the image service, if you make your own, you lose those benefits unless you make it yourself - - -### Changed: default `scopedStyleStrategy` - -In Astro v2.x, the default value of `scopedStyleStrategy` was `"where"`. - -Astro v3.0, the default value is `"attribute"`. By default, styles are now applied using `data-*` attributes. - -#### What should I do? - -To retain your project's current style scoping, update the configuration file to the previous default value: - -```diff -export default defineConfig({ -+ scopedStyleStrategy: "where" -}) -``` - - - ### Changed: Multiple JSX framework configuration In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project and Astro without having to identify which files belonged to which framework. Astro automatically scanned your components to determine which framework-specific transformations should be used, but at a performance cost. From 0db35b1ece0bb39d837b6e7362a6df298bf4ea22 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 18:45:19 +0000 Subject: [PATCH 032/119] typo in trailingSlash --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index e58c02ad77b98..e356c02dbf8e6 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -246,7 +246,7 @@ Run the `astro check` command after upgrading to Astro v3.0 and follow the promp 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 does not appended `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. +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? From 736d767c76f6da51cdd07ee57315fb47d07db015 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 18:49:20 +0000 Subject: [PATCH 033/119] scoped style link --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index e356c02dbf8e6..94845e30ee4c3 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -291,7 +291,7 @@ Astro v3.0 introduces a new, default value: `"attribute"`. By default, styles ar #### What should I do? -To retain your project's current style scoping, update the configuration file to the previous default value: +To retain your project's current [style scoping](/en/guides/styling/#scoped-styles), update the configuration file to the previous default value: ```ts title="astro.config.mjs" ins={4} From 389d6a3638c4aba3591bb0113a6edcf655dacb56 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 19:16:00 +0000 Subject: [PATCH 034/119] inlineStyleSheets plus code example syntax fixes up to here --- src/content/docs/en/guides/upgrade-to/v3.mdx | 56 ++++++++++---------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 94845e30ee4c3..8b43911f07166 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -149,9 +149,8 @@ Astro v3.0 completely removes the package `@astrojs/markdown-component`. Astro's Remove all instances of the `@astrojs/markdown-component`. -```astro del={3} +```astro del={2} title="src/components/MyAstroComponent.astro" --- -// astro.config.mjs import Markdown from '@astrojs/markdown-component'; --- ``` @@ -170,7 +169,7 @@ Astro v3.0 replaces these build config options with new [SSR adapter configurati Update the Astro config file to now use the new options **in the adapter configuration** directly. -```astro title="astro.config.mjs" del={5-7} ins={9} +```js title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import vercel from "@astrojs/vercel/serverless"; @@ -184,7 +183,7 @@ export default defineConfig({ }); ``` -```astro title="astro.config.mjs" del={5-7} ins={9} +```js title="astro.config.mjs" del={5-7} ins={9} import { defineConfig } from "astro/config"; import netlify from "@astrojs/netlify/functions"; @@ -222,11 +221,11 @@ const myValue = "red" 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: -```diff +```astro del={3} ins={4} title="src/components/MyAstroComponent.astro" <style> div { -- color: var(--my-value); -+ color: var(--myValue); + color: var(--my-value); + color: var(--myValue); } </style> ``` @@ -254,7 +253,7 @@ 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"`) behaviour: -```astro title="astro.config.mjs" del={4} ins={5} +```js title="astro.config.mjs" del={4} ins={5} import { defineConfig } from "astro/config"; export default defineConfig({ @@ -273,7 +272,7 @@ Astro v3.0 now compresses emitted HTML by default. You can now remove `compressHTML: true` from your configuration as this is the new default behavior. -```ts title="astro.config.mjs" del={4} +```js title="astro.config.mjs" del={4} import { defineConfig } from "astro/config"; export default defineConfig({ @@ -294,7 +293,7 @@ Astro v3.0 introduces a new, default value: `"attribute"`. By default, styles ar To retain your project's current [style scoping](/en/guides/styling/#scoped-styles), update the configuration file to the previous default value: -```ts title="astro.config.mjs" ins={4} +```js title="astro.config.mjs" ins={4} import { defineConfig } from "astro/config"; export default defineConfig({ @@ -302,6 +301,25 @@ export default defineConfig({ }) ``` +### Changed default: `inlineStyleSheets` + +In Astro v2.x, all project stylesheets were sent as link tags by default. You could opt in to `"always"` inlining them into `<style>` tags, or to `"auto"`matically inlining only stylesheets below a certain size 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: automatic flattening of `getStaticPaths()`'s return value @@ -486,24 +504,6 @@ These are entrypoints for Astro's internal API and should not affect your projec + import 'astro/runtime/server/index.js'; ``` -### Small stylesheets now get inlined by default -In Astro v2.x, all project stylesheets were sent lnd u could opt-in to inlining them by using the `build.inlineStylesheets` configuration. - -were sent as link tags by default and you could opt in to inlining them - -Astro v3.0 defaults `inlineStylesheets` to "auto", which means stylesheets smaller than 4kB get included in the initial response. - -#### What should I do? -Nothing, this change does not require any migration. To go back to the old behavior, configure `inlineStylesheets` to "never" - -```diff -export default defineConfig({ - build: { -+ inlineStylesheets: "never" - } -}) -``` - ### Changed implementation of `class:list` directive In Astro v2.x, `class:list` used a custom implementation inspired by [`clsx`](https://github.com/lukeed/clsx) with a few extra features like deduplication and `Set` support. From a0ef058bd50dfe05e98f38ebf5473ad9adb8d7b8 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 19:42:12 +0000 Subject: [PATCH 035/119] class:list entries --- src/content/docs/en/guides/upgrade-to/v3.mdx | 79 ++++++++++---------- 1 file changed, 41 insertions(+), 38 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 8b43911f07166..95f2a0861790f 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -230,6 +230,47 @@ If you were relying on Astro to transform kebab-case in your styles, update your </style> ``` +### 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]} +/> +``` + ### Moved: `astro check` is now 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. @@ -504,45 +545,7 @@ These are entrypoints for Astro's internal API and should not affect your projec + import 'astro/runtime/server/index.js'; ``` -### Changed implementation of `class:list` directive -In Astro v2.x, `class:list` used a custom implementation inspired by [`clsx`](https://github.com/lukeed/clsx) with a few extra features like deduplication and `Set` support. - -In Astro v3.0, `class:list` uses [`clsx`](https://github.com/lukeed/clsx) directly, 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`. - -```diff - <Component class:list={[ - 'a', - 'b', -- new Set(['c', 'd']) -+ ['c', 'd'] - ]} /> -``` - -### Changed behavior of `class:list` directive for components - -In Astro v2.x, `class:list` values were sent to components via `Astro.props['class:list']`. -In Astro v3.0, `class:list` values are normalized 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. - -```diff ---- -- import { clsx } from 'clsx'; -- const { class: className, 'class:list': classList } = Astro.props; -+ const { class: className } = Astro.props; ---- -<div -- class:list={[className, classList]} -+ class={className} -/> -``` ## Known Issues From aab8aaa2d9b6b9894b89f3bf105c0e310df16042 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 20:12:03 +0000 Subject: [PATCH 036/119] defalt port --- src/content/docs/en/guides/upgrade-to/v3.mdx | 21 ++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 95f2a0861790f..2cf8a9b8be806 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -282,6 +282,17 @@ Astro v3.0 moves the `astro check` command out of Astro core and now requires an 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. +### Changed default: port `3000` + +In Astro v2.x, Astro ran on port `3000` by default. + +Astro v3.0 changes the default port 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. @@ -454,16 +465,6 @@ if (id) { } ``` -### Changed: default port used - -In Astro v2.x, Astro ran on port `3000` by default. - -Astro v3.0 changes the default port 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`. - ### Added: simple asset support for Cloudflare, Deno, Vercel Edge and Netlify Edge In Astro v2.x, using the assets feature in Cloudflare, Deno, Vercel Edge and Netlify Edge errors in runtime as the environments do not support Astro's builtin Squoosh and Sharp image optimization. From 1717ef375fb277ce8da0524bfc04bbc47b459f14 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 20:25:39 +0000 Subject: [PATCH 037/119] getStaticPaths flattening entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 100 +++++++++---------- 1 file changed, 49 insertions(+), 51 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 2cf8a9b8be806..81972eb3550b4 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -197,39 +197,6 @@ export default defineConfig({ }); ``` -### Removed: kebab-case transform for camelCase CSS variables - -In Astro v2.x, camelCase CSS variables passed to the `style` attribute were rendered as both camelCase (as written) and kebab-case (kept for backwards compatibility). - -Astro 3.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: `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. @@ -271,6 +238,55 @@ const { class: className } = Astro.props; /> ``` +### Removed: kebab-case transform for camelCase CSS variables + +In Astro v2.x, camelCase CSS variables passed to the `style` attribute were rendered as both camelCase (as written) and kebab-case (kept for backwards compatibility). + +Astro 3.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 + +:::note[Example maybe?] +Do we want an example of returning an array of an array, requiring flattening? +::: + +In Astro v2.x, the return value of `getStaticPaths()` was automatically flattened to allow you to return an array of array 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` is now 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. @@ -373,24 +389,6 @@ export default defineConfig({ }) ``` -### Changed: automatic flattening of `getStaticPaths()`'s return value - -:::note[Example needed] -Find an example of returning an array of an array -::: - -In Astro v2.x, we would magically flatten the result of `getStaticPaths()` automatically for the user, so if you returned an array of array, it would still work - -Astro v3.0 we changed this in favour of the user doing it themselves when they need to, in line with how we typically prefer for users to do explicit things. - -Removed automatic flattening of getStaticPaths result. .flatMap and .flat should now be used to ensure that you’re returning a flat array. - -#### What should I do? - -If you're returning an array of arrays instead of an array of object (as you should), please flatten it using .flat(), or if you're using a .map(), use .flatMap() instead - -A [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. - ### Changed: default image service to Sharp instead of Squoosh In Astro v2.x, Squoosh was the default image service. From b5bead30421b1325190e7a04f0191c4e6acdd24b Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 20:38:08 +0000 Subject: [PATCH 038/119] internal API endpoints entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 28 +++++++++++++------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 81972eb3550b4..314dd84f8edaa 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -526,22 +526,32 @@ export default defineConfig({ }); ``` -### Changed entrypoint export paths +### Changed: internal Astro API entry point export paths -In Astro v2.x, you can import internal Astro APIs from `astro/internal/star` and `astro/runtime/server/star`. +In Astro v2.x, you could import internal Astro APIs from `astro/internal/*` and `astro/runtime/server/*`. -Astro v3.0 removes the two entrypoints in favour of the existing `astro/runtime/star` entrypoint. +Astro v3.0 removes the two entry points in favour 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 entrypoints for Astro's internal API and should not affect your project, but if you do use these entrypoints, you can migrate like below: +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: - ```diff - - import 'astro/internal/index.js'; - + import 'astro/runtime/server/index.js'; + ```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'; + 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', + // ... +}); ``` From 5117ac0215e8442550f260905ec7b3f87ed48aef Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 21:02:56 +0000 Subject: [PATCH 039/119] squoosh sharp --- src/content/docs/en/guides/upgrade-to/v3.mdx | 38 +++----------------- 1 file changed, 4 insertions(+), 34 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 314dd84f8edaa..2602528ff2aa2 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -389,19 +389,15 @@ export default defineConfig({ }) ``` -### Changed: default image service to Sharp instead of Squoosh +### Changed default: Squoosh image processing service -In Astro v2.x, Squoosh was the default image service. +In Astro v2.x, Squoosh was the default image processing service. -Astro v3.0, Sharp is now the 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? -Sharp is now the default image service used for Astro. - -You no longer need to install the dependency locally in your project. - -Uninstall Sharp using your package manager, or by removing manually from your `package.json`. +If you had previously installed Sharp, uninstall the dependency using your package manager, or by removing manually from your `package.json`. It is now included in Astro. If you would prefer to continue to use Squoosh to transform your images, update your config with the following: @@ -463,32 +459,6 @@ if (id) { } ``` -### Added: simple asset support for Cloudflare, Deno, Vercel Edge and Netlify Edge - In Astro v2.x, using the assets feature in Cloudflare, Deno, Vercel Edge and Netlify Edge errors in runtime as the environments do not support Astro's builtin Squoosh and Sharp image optimization. - - Astro v3.0 allows these environments to work without errors, but does not perform any image transformation and processing. However, you would still get benefits, e.g. no Cumulative Layout Shift (CLS), enforced alt attribute, etc. - - What should I do? - If you previously avoided the assets feature due these constraints, you can now use them without issues. You can also use the no-op image service to explicitly opt-in to this behaviour: - - ``` - // astro.config.mjs - export default { - image: { - service: { - entrypoint: 'astro/assets/services/noop' - } - } - } - ``` - -In Astro v2.x, you would get an error log in development. When building a project, the build would fail. - -Astro V3 still displays the error log, but now you can build the project. - -When using an adapter that supports neither Squoosh or Sharp, Astro will now automatically use an image service that does not support processing, but still provides the other benefits of `astro:assets` such as enforcing `alt`, no CLS etc to users. Should be noted that it does no transformations or processing, but you still get all the other benefits (no CLS, alt enforced, etc). All of those benefits are part of the image service, if you make your own, you lose those benefits unless you make it yourself - - ### Changed: Multiple JSX framework configuration In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project and Astro without having to identify which files belonged to which framework. Astro automatically scanned your components to determine which framework-specific transformations should be used, but at a performance cost. From aeecbc8a0280687eb9acc32cb253d79cb80587b7 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 21:34:43 +0000 Subject: [PATCH 040/119] HTTP request methods and more links to this point --- src/content/docs/en/guides/upgrade-to/v3.mdx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 2602528ff2aa2..75a116aa4a807 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -240,7 +240,7 @@ const { class: className } = Astro.props; ### Removed: kebab-case transform for camelCase CSS variables -In Astro v2.x, camelCase CSS variables passed to the `style` attribute were rendered as both camelCase (as written) and kebab-case (kept for backwards compatibility). +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 3.0 removes the kebab-case transform for these camelCase CSS variable names, and only the original camelCase CSS variable is rendered. @@ -277,7 +277,7 @@ If you were relying on Astro to transform kebab-case in your styles, update your Do we want an example of returning an array of an array, requiring flattening? ::: -In Astro v2.x, the return value of `getStaticPaths()` was automatically flattened to allow you to return an array of array without errors. +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 array without errors. Astro v3.0 removes automatic flattening of `getStaticPaths()`'s result. @@ -302,7 +302,7 @@ Run the `astro check` command after upgrading to Astro v3.0 and follow the promp In Astro v2.x, Astro ran on port `3000` by default. -Astro v3.0 changes the default port to `4321`. 🚀 +Astro v3.0 changes the [default port](/en/reference/cli-reference/#--port-number) to `4321`. 🚀 #### What should I do? @@ -391,7 +391,7 @@ export default defineConfig({ ### Changed default: Squoosh image processing service -In Astro v2.x, Squoosh was the default image processing 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. @@ -411,15 +411,15 @@ export default defineConfig({ }) ``` -### Changed: casing in function endpoints +### Changed default: HTTP request methods -In Astro v2.x, endpoints were defined using lowercase function names: `get`, `post`, `put`, `all`, and `del`. +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. +Astro v3.0 uses uppercase function names, including `DELETE` instead of `del`. #### What should I do? -Rename functions to uppercase equivalent: +Rename all functions to their uppercase equivalent: - `get` to `GET` - `post` to `POST` @@ -427,7 +427,7 @@ Rename functions to uppercase equivalent: - `all` to `ALL` - `del` to `DELETE` -```ts title="endpoint.ts" del={1} ins={2} +```js title="endpoint.ts" del={1} ins={2} export function get() { export function GET() { return new Response(JSON.stringify({ "title": "Bob's blog" })); From 00e61238c8bdd392d473f5671582fceebc6abf76 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 21:37:28 +0000 Subject: [PATCH 041/119] shortened image service title --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 75a116aa4a807..86008738e122b 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -389,7 +389,7 @@ export default defineConfig({ }) ``` -### Changed default: Squoosh image processing service +### Changed default: image service In Astro v2.x, Squoosh was the [default image processing service](/en/guides/images/#default-image-service). From cd4ef96396c344cf5f5697531caeae5ef0d68e5d Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 21:50:30 +0000 Subject: [PATCH 042/119] astro.cookies entry --- src/content/docs/en/guides/upgrade-to/v3.mdx | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 86008738e122b..587137322a54f 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -434,28 +434,25 @@ export function GET() { } ``` -### Changed: Behaviour when `Astro.cookies.get(key)` doesn't exist +### Added: `Astro.cookies.get(key)` can return `undefined` -In Astro v2.x, `Astro.cookies.get(key)` would always return a `AstroCookie` object, even if the cookie did not exist. To check for the existence you needed to use `Astro.cookies.has(key)`. +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 `Astro.cookies.get(key)` will return `undefined` if the cookie does not exist. +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 existing code that checks for the existance of the `Astro.cookie` object before using `Astro.cookies.get(key)`, but is now no longer required. You can safely remove this code. +This change will not break existing code that checks for the existance of the `Astro.cookie` object before using `Astro.cookies.get(key)`, but is now no longer required. -You can safely skip `has()` and check if the value is `undefined`: +You can safely remove any code that uses `has()` to check if the value of `Astro.cookies` is `undefined`: -```ts -// before: +```js del={1-3} ins={5-7} if (Astro.cookies.has(id)) { const id = Astro.cookies.get(id)!; } -//after: const id = Astro.cookies.get(id); if (id) { - // TypeScript knows id is an AstroCookie } ``` From 714b5cb221ffb27a3c5cc7297f0e91c72cd27383 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Sat, 19 Aug 2023 22:07:14 +0000 Subject: [PATCH 043/119] final draft done!! --- src/content/docs/en/guides/upgrade-to/v3.mdx | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 587137322a54f..8369d51831045 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -411,7 +411,7 @@ export default defineConfig({ }) ``` -### Changed default: HTTP request methods +### 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`. @@ -434,37 +434,15 @@ export function GET() { } ``` -### Added: `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 existing code that checks for the existance 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: Multiple JSX framework configuration -In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project and Astro without having to identify which files belonged to which framework. Astro automatically scanned your components to determine which framework-specific transformations should be used, but at a performance cost. +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 determines which framework to use with `include` and `exclude` integration config options where you can specify files and folders on a per-framework basis. This allows Astro to better support single-framework usage, as well as advanced features like Fast Refresh. +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, use the `include` and/or `exclude` configuration options to specify which files belong to which framework. Provide an array of files and/or folders. Wildcards may be used to include multiple file paths. +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: @@ -493,6 +471,28 @@ export default defineConfig({ }); ``` +### 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 existing code that checks for the existance 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: internal Astro API entry point export paths In Astro v2.x, you could import internal Astro APIs from `astro/internal/*` and `astro/runtime/server/*`. From ea80c14a3ea84a7431930b1b42919d8184fbe0dd Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa <my.burning@gmail.com> Date: Mon, 21 Aug 2023 13:53:55 +0100 Subject: [PATCH 044/119] feat: document adapter features (#3917) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elian ☕️ <hello@elian.codes> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> --- .../docs/en/reference/adapter-reference.mdx | 190 +++++++++++++++--- 1 file changed, 163 insertions(+), 27 deletions(-) diff --git a/src/content/docs/en/reference/adapter-reference.mdx b/src/content/docs/en/reference/adapter-reference.mdx index 54974665714f2..d059d5ccfbca7 100644 --- a/src/content/docs/en/reference/adapter-reference.mdx +++ b/src/content/docs/en/reference/adapter-reference.mdx @@ -43,44 +43,58 @@ The object passed into `setAdapter` is defined as: ```ts interface AstroAdapter { - name: string; - serverEntrypoint?: string; - exports?: string[]; + name: string; + serverEntrypoint?: string; + exports?: string[]; + adapterFeatures: AstroAdapterFeatures; supportedAstroFeatures: AstroFeatureMap; -} -export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; +} -export type AstroFeatureMap = { - /** - * The adapter is able to serve static pages - */ - staticOutput?: SupportsKind; +export interface AstroAdapterFeatures { /** - * The adapter is able to serve pages that are static or rendered via server + * Creates an edge function that will communicate with the Astro middleware. */ - hybridOutput?: SupportsKind; + edgeMiddleware: boolean; /** - * The adapter is able to serve SSR pages + * SSR only. Each route becomes its own function/file. */ - serverOutput?: SupportsKind; - /** - * The adapter can emit static assets - */ - assets?: AstroAssetsFeature; + functionPerRoute: boolean; +} + +export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; + +export type AstroFeatureMap = { + /** + * The adapter is able to serve static pages + */ + staticOutput?: SupportsKind; + /** + * The adapter is able to serve pages that are static or rendered via server + */ + hybridOutput?: SupportsKind; + /** + * The adapter is able to serve SSR pages + */ + serverOutput?: SupportsKind; + /** + * The adapter can emit static assets + */ + assets?: AstroAssetsFeature; }; export interface AstroAssetsFeature { - supportKind?: SupportsKind; - /** - * Whether or not this adapter deploys files in an environment that is compatible with the library `sharp` - */ - isSharpCompatible?: boolean; - /** - * Whether or not this adapter deploys files in an environment that is compatible with the library `squoosh` - */ - isSquooshCompatible?: boolean; + supportKind?: SupportsKind; + /** + * Whether this adapter deploys files in an environment that is compatible with the library `sharp` + */ + isSharpCompatible?: boolean; + /** + * Whether this adapter deploys files in an environment that is compatible with the library `squoosh` + */ + isSquooshCompatible?: boolean; } + ``` The properties are: @@ -88,6 +102,8 @@ The properties are: * __name__: A unique name for your adapter, used for logging. * __serverEntrypoint__: The entrypoint for server-side rendering. * __exports__: An array of named exports when used in conjunction with `createExports` (explained below). +* __adapterFeatures__: An object that enables specific features that must be supported by the adapter. + These features will change the built output, and the adapter must implement the proper logic to handle the different output. * __supportedAstroFeatures__: A map of Astro built-in features. This allows Astro to determine which features an adapter is unable or unwilling to support so appropriate error messages can be provided. ### Server Entrypoint @@ -278,3 +294,123 @@ and an error if the service used for assets is not compatible with the adapter: ``` [@matthewp/my-adapter] The currently selected adapter `@matthewp/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build. ``` + +## Adapter features + +A set of features that changes the output of the emitted files. When an adapter opts in to these features, they will get additional information inside specific hooks. + +### `functionPerRoute` + +This is a feature that is enabled when using SSR only. By default, Astro emits a single `entry.mjs` file, which is responsible for emitting the rendered page on each request. + +When `functionPerRoute` is `true`, Astro will instead create a separate file for each route defined in the project. +Each file emitted will only render one page. The pages will be emitted inside a `dist/pages/` directory, and the emitted files will keep the same file paths of the `src/pages/` directory. + +Enable the feature by passing `true` to the adapter. + +```js title="my-adapter.mjs" ins={9-11} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + functionPerRoute: true + } + }); + }, + }, + }; +} +``` + +Then, consume the hook [`astro:build:ssr`](/en/reference/integrations-reference/#astrobuildssr), which will give you an `entryPoints` object that maps a page route to the physical file emitted after the build. + +```js title="my-adapter.mjs" ins={15-19} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + functionPerRoute: true + } + }); + }, + + 'astro:build:ssr': ({ entryPoints }) => { + for (const [route, entryFile] of entryPoints) { + // do something with route and entryFile + } + } + }, + }; +} +``` + +:::caution +The `entryFile` is of type `URL` and represents the physical path of the file in the file system. This means that the paths change based on the OS where the code runs. +::: + +### `edgeMiddleware` + +Defines whether any SSR middleware code will be bundled when built. + +When enabled, this prevents middleware code from being bundled and imported by all pages during the build: + +```js title="my-adapter.mjs" ins={9-11} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + edgeMiddleware: true + } + }); + }, + }, + }; +} +``` + +Then, consume the hook [`astro:build:ssr`](/en/reference/integrations-reference/#astrobuildssr), which will give you a `middlewareEntryPoint`, an `URL` to the physical file on the file system. + +```js title="my-adapter.mjs" ins={15-19} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + edgeMiddleware: true + } + }); + }, + + 'astro:build:ssr': ({ middlewareEntryPoint }) => { + // remember to check if this property exits, it will be `undefined` if the adapter doesn't opt in to the feature + if (middlewareEntryPoint) { + createEdgeMiddleware(middlewareEntryPoint) + } + } + }, + }; +} + +function createEdgeMiddleware(middlewareEntryPoint) { + // emit a new physical file using your bundler +} +``` From e58d9d9b392e44b94ed8663ea5f19cd7bdb8db65 Mon Sep 17 00:00:00 2001 From: = <otterlord.dev@gmail.com> Date: Mon, 21 Aug 2023 15:29:55 +0100 Subject: [PATCH 045/119] Update capitalisation of GET --- src/content/docs/en/guides/integrations-guide/cloudflare.mdx | 2 +- src/content/docs/en/guides/integrations-guide/netlify.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx index 0d5d4b4cf0dfa..5ca718d01f493 100644 --- a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx @@ -109,7 +109,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/netlify.mdx b/src/content/docs/en/guides/integrations-guide/netlify.mdx index bd5e6fd987ec5..7cd84245495bf 100644 --- a/src/content/docs/en/guides/integrations-guide/netlify.mdx +++ b/src/content/docs/en/guides/integrations-guide/netlify.mdx @@ -274,7 +274,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 From 873d99c93911092080a1c2788a6d249decbec4de Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Mon, 21 Aug 2023 16:56:59 -0300 Subject: [PATCH 046/119] Apply suggestions from EVERYONE's code review! Co-authored-by: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> Co-authored-by: Kevin Zuniga Cuellar <46791833+kevinzunigacuellar@users.noreply.github.com> Co-authored-by: Bjorn Lu <bjornlu.dev@gmail.com> Co-authored-by: Erika <3019731+Princesseuh@users.noreply.github.com> Co-authored-by: Shinya Fujino <shf0811@gmail.com> --- src/content/docs/en/guides/upgrade-to/v3.mdx | 50 ++++++++++---------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 8369d51831045..dba1ae50cd648 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -80,11 +80,11 @@ See [the changelog](https://github.com/withastro/astro/blob/main/packages/astro/ 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. +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 later**. + 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: @@ -92,13 +92,15 @@ Astro v3.0 drops Node 16 support entirely, so that all Astro users can take adva node -v ``` - If your local development environment needs upgrading, [install Node](https://nodejs.org/en/download/). 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. + 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. @@ -121,7 +123,7 @@ Astro v3.0 removes this integration from the codebase entirely. Astro's new solu #### 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. +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. @@ -141,7 +143,7 @@ export default defineConfig({ ### Removed: `<Markdown />` component -In Astro v2.x, Astro deprecated the `<Markdown />` component and moved it to an external package. +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. @@ -277,7 +279,7 @@ If you were relying on Astro to transform kebab-case in your styles, update your Do we want an example of returning an array of an array, requiring flattening? ::: -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 array without errors. +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. @@ -287,9 +289,9 @@ If you're returning an array of arrays instead of an array of _objects_ (as is e 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` is now an external package +### 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. +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. @@ -311,7 +313,7 @@ Update any existing references to `localhost:3000`, for example in tests or in y ### 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. +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.) @@ -319,7 +321,7 @@ Astro v3.0 no longer appends `import.meta.env.BASE_URL` with a trailing slash by 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"`) behaviour: +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"; @@ -371,7 +373,7 @@ export default defineConfig({ ### Changed default: `inlineStyleSheets` -In Astro v2.x, all project stylesheets were sent as link tags by default. You could opt in to `"always"` inlining them into `<style>` tags, or to `"auto"`matically inlining only stylesheets below a certain size by setting the [`build.inlineStylesheets`](/en/reference/configuration-reference/#buildinlinestylesheets) configuration. The default setting was `"never"`. +In Astro v2.x, all project stylesheets were sent as link tags by default. You could opt in to inlining them into `<style>` tags everytime 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. @@ -393,7 +395,7 @@ export default defineConfig({ 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. +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? @@ -479,7 +481,7 @@ Astro v3.0 returns `undefined` for `Astro.cookies.get(key)` if the cookie does n #### What should I do? -This change will not break existing code that checks for the existance of the `Astro.cookie` object before using `Astro.cookies.get(key)`, but is now no longer required. +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`: @@ -497,29 +499,29 @@ if (id) { 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 favour of the existing `astro/runtime/*` entrypoint. Additionally, a new `astro/compiler-runtime` export has been added for compiler-specific runtime code. +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'; +```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'; +import 'astro/server/index.js'; +import 'astro/runtime/server/index.js'; ``` - ```js ins={5} del={4} +```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', + internalURL: 'astro/runtime/server/index.js', + internalURL: 'astro/compiler-runtime', // ... }); - ``` +``` From 4d76d73766b39195d8e791505e23845f886d6b69 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Mon, 21 Aug 2023 17:01:22 -0300 Subject: [PATCH 047/119] Touche, Matthew. Co-authored-by: Matthew Phillips <matthew@skypack.dev> --- src/content/docs/en/reference/integrations-reference.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/en/reference/integrations-reference.mdx b/src/content/docs/en/reference/integrations-reference.mdx index 42cc5d7a98d69..e42e92c96ca8f 100644 --- a/src/content/docs/en/reference/integrations-reference.mdx +++ b/src/content/docs/en/reference/integrations-reference.mdx @@ -540,10 +540,10 @@ An instance of the Astro logger, useful to write logs. This logger uses the same configured via CLI. **Methods available** to write to terminal: -- `logger.info("Messsage")`; -- `logger.warn("Messsage")`; -- `logger.error("Messsage")`; -- `logger.debug("Messsage")`; +- `logger.info("Message")`; +- `logger.warn("Message")`; +- `logger.error("Message")`; +- `logger.debug("Message")`; All the messages are prepended with a label that has the same value of the integration. From 09309f3c40619f3e00233938c65526a5c5716dbb Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Mon, 21 Aug 2023 17:43:27 -0300 Subject: [PATCH 048/119] Every time someone has a good idea, we commit! Co-authored-by: J. B. Rainsberger <me@jbrains.ca> --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index dba1ae50cd648..2bcbbde07d28a 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -373,7 +373,7 @@ export default defineConfig({ ### 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 everytime 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"`. +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. From 2f1fdf4dceed48f1cf8730a475e770286af378c0 Mon Sep 17 00:00:00 2001 From: Bjorn Lu <bjornlu.dev@gmail.com> Date: Tue, 22 Aug 2023 06:44:04 +0800 Subject: [PATCH 049/119] Document experimental JS API (#4234) Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> --- .../docs/en/reference/cli-reference.mdx | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/src/content/docs/en/reference/cli-reference.mdx b/src/content/docs/en/reference/cli-reference.mdx index 79f29ba0c085c..8ec7b2ccc255c 100644 --- a/src/content/docs/en/reference/cli-reference.mdx +++ b/src/content/docs/en/reference/cli-reference.mdx @@ -373,3 +373,129 @@ Automatically opens the app in the browser on server start. ### `--help` Prints the help message and exits. + +## Advanced APIs (Experimental) + +If you need more control when running Astro, the `"astro"` package also exports APIs to programmatically run the CLI commands. + +These APIs are experimental and their API signature may change. Any updates will be mentioned in the [Astro changelog](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md) and the information below will always show the current, up-to-date information. + +### `AstroInlineConfig` + +The `AstroInlineConfig` type is used by all of the command APIs below. It extends from the user [Astro config](/en/reference/configuration-reference/) type: + +```ts +interface AstroInlineConfig extends AstroUserConfig { + configFile?: string | false; + mode?: "development" | "production"; + logLevel?: "debug" | "info" | "warn" | "error" | "silent"; +} +``` + +#### `configFile` + +<p> + +**Type:** `string | false`<br /> +**Default:** `undefined` +</p> + +A custom path to the Astro config file. + +If this value is undefined (default) or unset, Astro will search for an `astro.config.(js,mjs,ts)` file relative to the `root` and load the config file if found. + +If a relative path is set, it will resolve based on the current working directory. + +Set to `false` to disable loading any config files. + +The inline config passed in this object will take highest priority when merging with the loaded user config. + +#### `mode` + +<p> + +**Type:** `"development" | "production"`<br /> +**Default:** `"development"` when running `astro dev`, `"production"` when running `astro build` +</p> + +The mode used when building your site to generate either "development" or "production" code. + +#### `logLevel` + +<p> + +**Type:** `"debug" | "info" | "warn" | "error" | "silent"`<br /> +**Default:** `"info"` +</p> + +The logging level to filter messages logged by Astro. + +- `"debug"`: Log everything, including noisy debugging diagnostics. +- `"info"`: Log informational messages, warnings, and errors. +- `"warn"`: Log warnings and errors. +- `"error"`: Log errors only. +- `"silent"`: No logging. + +### `dev()` + +**Type:** `(inlineConfig: AstroInlineConfig) => AstroDevServer` + +Similar to [`astro dev`](#astro-dev), it runs Astro's development server. + +```js +import { dev } from "astro"; + +const devServer = await dev({ + root: "./my-project", +}); + +// Stop the server if needed +await devServer.stop(); +``` + +### `build()` + +**Type:** `(inlineConfig: AstroInlineConfig) => void` + +Similar to [`astro build`](#astro-build), it builds your site for deployment. + +```js +import { build } from "astro"; + +await build({ + root: "./my-project", +}); +``` + +### `preview()` + +**Type:** `(inlineConfig: AstroInlineConfig) => AstroPreviewServer` + +Similar to [`astro preview`](#astro-preview), it starts a local server to serve your static `dist/` directory. + +```js +import { preview } from "astro"; + +const previewServer = await preview({ + root: "./my-project", +}); + +// Stop the server if needed +await previewServer.stop(); +``` + +### `sync()` + +**Type:** `(inlineConfig: AstroInlineConfig) => number` + +Similar to [`astro sync`](#astro-sync), it generates TypeScript types for all Astro modules + +```js +import { sync } from "astro"; + +const exitCode = await sync({ + root: "./my-project", +}); + +process.exit(exitCode) +``` From 41b02504e8ddbd6519292085b28371a94154eb60 Mon Sep 17 00:00:00 2001 From: Matthew Phillips <matthew@skypack.dev> Date: Tue, 22 Aug 2023 09:27:58 -0400 Subject: [PATCH 050/119] Update Firebase example to use cookies.has() (#4302) Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> Co-authored-by: Reuben Tier <64310361+TheOtterlord@users.noreply.github.com> --- .../docs/en/guides/backend/google-firebase.mdx | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/content/docs/en/guides/backend/google-firebase.mdx b/src/content/docs/en/guides/backend/google-firebase.mdx index 3a091262c7257..4509287087200 100644 --- a/src/content/docs/en/guides/backend/google-firebase.mdx +++ b/src/content/docs/en/guides/backend/google-firebase.mdx @@ -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"); From c50bba3c530ad31b1e5a7f20d13949d8dd7e43ee Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Tue, 22 Aug 2023 16:29:53 +0000 Subject: [PATCH 051/119] last new entries for upgrade guide! Code freeze! --- src/content/docs/en/guides/upgrade-to/v3.mdx | 83 ++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 2bcbbde07d28a..4d468c0b4694d 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -161,6 +161,57 @@ To continue using a similar `<Markdown />` component in your code, consider usin 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 v2.x, 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) + +### Changed: validating `image` in content collections schema + +In Astro 2.x, the content collections API deprecated an `image` export from `astro:content` for use in your content collections schemas. + +Astro 3.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 favour 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: `build.excludeMiddleware` and `build.split` In Astro v2.x, `build.excludeMiddleware` and `build.split` could be used to change how specific files were emitted when using an adapter in SSR mode. @@ -300,6 +351,16 @@ Astro v3.0 moves the `astro check` command out of Astro core and now requires an 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: `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 favour 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. + ### Changed default: port `3000` In Astro v2.x, Astro ran on port `3000` by default. @@ -495,6 +556,28 @@ 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/*`. From 17a8228b94bd746dfada591a098ce66142434bb5 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Tue, 22 Aug 2023 13:40:12 -0300 Subject: [PATCH 052/119] Mostly formatting catches, also build config DEPRECATED and line highlighting Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> Co-authored-by: Shinya Fujino <shf0811@gmail.com> --- src/content/docs/en/guides/upgrade-to/v3.mdx | 26 ++++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 4d468c0b4694d..358fa0cc9b05a 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -212,7 +212,7 @@ If your project uses any of the themes below, rename them to their updated name: - `material-ocean` -> `material-theme-ocean` - `material-palenight` -> `material-theme-palenight` -### Removed: `build.excludeMiddleware` and `build.split` +### Deprecated: `build.excludeMiddleware` and `build.split` In Astro v2.x, `build.excludeMiddleware` and `build.split` could be used to change how specific files were emitted when using an adapter in SSR mode. @@ -407,7 +407,7 @@ You can now remove `compressHTML: true` from your configuration as this is the n import { defineConfig } from "astro/config"; export default defineConfig({ - compressHTML: true + compressHTML: true }) ``` @@ -428,7 +428,7 @@ To retain your project's current [style scoping](/en/guides/styling/#scoped-styl import { defineConfig } from "astro/config"; export default defineConfig({ - scopedStyleStrategy: "where" + scopedStyleStrategy: "where" }) ``` @@ -509,7 +509,7 @@ If you are using multiple JSX frameworks in the same project, set `include` (and 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 +```js ins={13,16,19} import { defineConfig } from 'astro/config'; import preact from '@astrojs/preact'; import react from '@astrojs/react'; @@ -521,15 +521,15 @@ 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/*'], - }), + preact({ + include: ['**/preact/*'] + }), + react({ + include: ['**/react/*'] + }), + solid({ + include: ['**/solid/*'], + }), ] }); ``` From 740d821ed63d114f052dc76b6dc57f7411fa80e2 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Tue, 22 Aug 2023 13:50:23 -0300 Subject: [PATCH 053/119] missed a formatting correction Co-authored-by: Emanuele Stoppa <my.burning@gmail.com> --- src/content/docs/en/reference/adapter-reference.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/docs/en/reference/adapter-reference.mdx b/src/content/docs/en/reference/adapter-reference.mdx index d059d5ccfbca7..6d5eb92878d6a 100644 --- a/src/content/docs/en/reference/adapter-reference.mdx +++ b/src/content/docs/en/reference/adapter-reference.mdx @@ -272,8 +272,8 @@ export default function createIntegration() { supportedAstroFeatures: { assets: { supportKind: "experimental", - isSharpCompatible: false, - isSquooshCompatible: false + isSharpCompatible: false, + isSquooshCompatible: false } } }); From 98f8f99248bdf8f992967091a3c210dce4bc3364 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Tue, 22 Aug 2023 16:58:04 +0000 Subject: [PATCH 054/119] moves build config options down to deprecated section --- src/content/docs/en/guides/upgrade-to/v3.mdx | 78 ++++++++++---------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 358fa0cc9b05a..f7311e15215d6 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -174,7 +174,7 @@ If you are continuing to use v1.x APIs, use the new APIs for each feature instea - 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) -### Changed: validating `image` in content collections schema +### Removed: `image` from `astro:content` in content collections schema In Astro 2.x, the content collections API deprecated an `image` export from `astro:content` for use in your content collections schemas. @@ -212,44 +212,6 @@ If your project uses any of the themes below, rename them to their updated name: - `material-ocean` -> `material-theme-ocean` - `material-palenight` -> `material-theme-palenight` -### Deprecated: `build.excludeMiddleware` and `build.split` - -In Astro v2.x, `build.excludeMiddleware` and `build.split` could be 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 - }), -}); -``` - ### 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. @@ -351,6 +313,44 @@ Astro v3.0 moves the `astro check` command out of Astro core and now requires an 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. From 0412b2eab65ec6274580e213ecd59c06a7945ad7 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 08:22:45 -0300 Subject: [PATCH 055/119] bluwy nits! Co-authored-by: Bjorn Lu <bjornlu.dev@gmail.com> --- src/content/docs/en/guides/upgrade-to/v3.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index f7311e15215d6..c55f66dcb76fb 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -163,7 +163,7 @@ Otherwise, delete all references to importing Astro's `<Markdown />` component a ### Removed: deprecated 1.x APIs -In Astro v2.x, deprecated config options as well as script/style `global` and `hoist` attributes types. These were kept for backwards compatibility. +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. @@ -185,7 +185,7 @@ Astro 3.0 removes this export entirely. 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, image } from "astro:content"; import { defineCollection, z } from "astro:content"; defineCollection({ From b41a7ba8e16f978478adae12c01fcda04fa33a23 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 08:26:54 -0300 Subject: [PATCH 056/119] earlier link to image upgrade advice --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index c55f66dcb76fb..fb232bd550bba 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -64,7 +64,7 @@ export default defineConfig({ These features are now available by default: - [View Transitions](/en/guides/view-transitions/) for animated page transitions and persistent islands. -- A new image services API `astro:assets` for [using images in Astro](/en/guides/images/), including a new `<Image />` component and `getImage()` function. +- A new image services API `astro:assets` for [using images in Astro](/en/guides/images/), including a new `<Image />` component and `getImage()` function. Please read the detailed [image upgrade advice](/en/guides/images/#upgrade-to-v30-from-v2x) to see how this might affect your project. Read more about these two exciting features and more in the 3.0 Blog post! From e164c3751f952e5513acc1fc5d75250c5c7efd1b Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 11:44:56 +0000 Subject: [PATCH 057/119] upgrade node version to 18.14.1 in English files only --- src/content/docs/en/guides/deploy/netlify.mdx | 2 +- src/content/docs/en/guides/deploy/render.mdx | 2 +- src/content/docs/en/guides/deploy/vercel.mdx | 2 +- src/content/docs/en/install/auto.mdx | 2 +- src/content/docs/en/install/manual.mdx | 2 +- src/content/docs/en/tutorial/1-setup/1.mdx | 8 ++++---- 6 files changed, 9 insertions(+), 9 deletions(-) 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/install/auto.mdx b/src/content/docs/en/install/auto.mdx index 9247a3bd0af4f..1f196f7d2056b 100644 --- a/src/content/docs/en/install/auto.mdx +++ b/src/content/docs/en/install/auto.mdx @@ -13,7 +13,7 @@ Read our [step-by-step manual installation guide](/en/install/manual/) instead. ::: #### Prerequisites -- **Node.js** - `v16.12.0` or higher. +- **Node.js** - `v18.14.1` or higher. - **Text editor** - We recommend [VS Code](https://code.visualstudio.com/) with our [Official Astro extension](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode). - **Terminal** - Astro is accessed through its command-line interface (CLI). diff --git a/src/content/docs/en/install/manual.mdx b/src/content/docs/en/install/manual.mdx index d6a6ebd909536..af3b88279a5aa 100644 --- a/src/content/docs/en/install/manual.mdx +++ b/src/content/docs/en/install/manual.mdx @@ -16,7 +16,7 @@ This guide will walk you through the steps to manually install and configure a n #### Prerequisites -- **Node.js** - `v16.12.0` or higher. +- **Node.js** - `v18.14.1` or higher. - **Text editor** - We recommend [VS Code](https://code.visualstudio.com/) with our [Official Astro extension](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode). - **Terminal** - Astro is accessed through its command-line interface (CLI). diff --git a/src/content/docs/en/tutorial/1-setup/1.mdx b/src/content/docs/en/tutorial/1-setup/1.mdx index 18c22ec86899f..2646b204706d0 100644 --- a/src/content/docs/en/tutorial/1-setup/1.mdx +++ b/src/content/docs/en/tutorial/1-setup/1.mdx @@ -29,7 +29,7 @@ You can access the command line through a local terminal program for your operat ### Node.js -For Astro to run on your system, you will also need to have [**Node.js**](https://nodejs.org/en/) installed, version `v16.12.0` or later. +For Astro to run on your system, you will also need to have [**Node.js**](https://nodejs.org/en/) installed, version `v18.14.1` or later. To check to see whether you already have a compatible version installed, run the following command in your terminal: @@ -37,12 +37,12 @@ To check to see whether you already have a compatible version installed, run the node -v // Example output -v16.14.0 +v18.14.1 ``` -If the command returns a version number higher than `v16.12.0`, you're good to go! +If the command returns a version number higher than `v18.14.1`, you're good to go! -If the command returns an error message like `Command 'node' not found`, or a version number lower than `v16.12.0`, then you need to [install a compatible Node.js version](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). +If the command returns an error message like `Command 'node' not found`, or a version number lower than `v18.14.1`, then you need to [install a compatible Node.js version](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). ### Code Editor From f71a9398ffdc2094f0b230898b0e3b27627ef3f4 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 12:28:42 +0000 Subject: [PATCH 058/119] removed examples that listed astrojs/image --- src/content/docs/en/concepts/why-astro.mdx | 2 +- src/content/docs/en/guides/integrations-guide.mdx | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/content/docs/en/concepts/why-astro.mdx b/src/content/docs/en/concepts/why-astro.mdx index 169178283e93a..759ba2f542478 100644 --- a/src/content/docs/en/concepts/why-astro.mdx +++ b/src/content/docs/en/concepts/why-astro.mdx @@ -75,6 +75,6 @@ One of our favorite sayings is: **opt-in to complexity.** We designed Astro to r **Astro is an all-in-one web framework that comes with everything you need to build a website.** Astro includes a component syntax, file-based routing, asset handling, a build process, bundling, optimizations, data-fetching, and more. You can build great websites without ever reaching outside of Astro's core feature set. -If you need more control, you can extend Astro with over [100+ integrations](https://astro.build/integrations/) like [React](https://www.npmjs.com/package/@astrojs/react), [Svelte](https://www.npmjs.com/package/@astrojs/svelte), [Vue](https://www.npmjs.com/package/@astrojs/vue), [Tailwind CSS](https://www.npmjs.com/package/@astrojs/tailwind), [MDX](https://www.npmjs.com/package/@astrojs/mdx), [image optimizations](https://www.npmjs.com/package/@astrojs/image), and more. [Connect your favorite CMS](/en/guides/cms/) or [deploy to your favorite host](/en/guides/deploy/) with just a single command. +If you need more control, you can extend Astro with over [100+ integrations](https://astro.build/integrations/) like [React](https://www.npmjs.com/package/@astrojs/react), [Svelte](https://www.npmjs.com/package/@astrojs/svelte), [Vue](https://www.npmjs.com/package/@astrojs/vue), [Tailwind CSS](https://www.npmjs.com/package/@astrojs/tailwind), [MDX](https://www.npmjs.com/package/@astrojs/mdx), and more. [Connect your favorite CMS](/en/guides/cms/) or [deploy to your favorite host](/en/guides/deploy/) with just a single command. Astro is UI-agnostic, meaning you can **Bring Your Own UI Framework (BYOF)**. React, Preact, Solid, Svelte, Vue, and Lit are all officially supported in Astro. You can even mix and match different frameworks on the same page, making future migrations easier and preventing project lock-in to a single framework. diff --git a/src/content/docs/en/guides/integrations-guide.mdx b/src/content/docs/en/guides/integrations-guide.mdx index 2a512ca2dd279..6244689988ce2 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 <PackageManagerTabs> <Fragment slot="npm"> ```shell - npm uninstall @astrojs/image + npm uninstall @astrojs/react ``` </Fragment> <Fragment slot="pnpm"> ```shell - pnpm uninstall @astrojs/image + pnpm uninstall @astrojs/react ``` </Fragment> <Fragment slot="yarn"> ```shell - yarn remove @astrojs/image + yarn remove @astrojs/react ``` </Fragment> </PackageManagerTabs> @@ -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 image from "@astrojs/react"; export default defineConfig({ integrations: [ - image() + react() ] }) ``` From 03df3a84bc5e708d0487dafec14c006640def484 Mon Sep 17 00:00:00 2001 From: Reuben Tier <64310361+TheOtterlord@users.noreply.github.com> Date: Wed, 23 Aug 2023 13:54:10 +0100 Subject: [PATCH 059/119] Generate v3 reference docs (#4327) --- .../guides/integrations-guide/cloudflare.mdx | 30 ++++-- .../en/guides/integrations-guide/netlify.mdx | 33 ++----- .../en/guides/integrations-guide/node.mdx | 2 +- .../en/guides/integrations-guide/preact.mdx | 35 +++++++ .../en/guides/integrations-guide/react.mdx | 33 +++++++ .../en/guides/integrations-guide/solid-js.mdx | 35 +++++++ .../en/guides/integrations-guide/vercel.mdx | 34 +++---- .../en/reference/configuration-reference.mdx | 92 +++++-------------- .../docs/en/reference/error-reference.mdx | 1 + .../errors/expected-image-options.mdx | 2 +- .../en/reference/errors/expected-image.mdx | 2 +- .../en/reference/errors/image-missing-alt.mdx | 6 +- .../errors/local-image-used-wrongly.mdx | 2 +- .../reference/errors/locals-not-an-object.mdx | 2 +- .../errors/markdown-image-not-found.mdx | 2 +- .../middleware-no-data-or-next-called.mdx | 2 +- .../errors/middleware-not-aresponse.mdx | 2 +- .../errors/missing-image-dimension.mdx | 4 +- .../en/reference/errors/missing-sharp.mdx | 37 ++++++++ .../errors/static-redirect-not-available.mdx | 2 +- .../errors/unsupported-image-format.mdx | 4 +- 21 files changed, 220 insertions(+), 142 deletions(-) create mode 100644 src/content/docs/en/reference/errors/missing-sharp.mdx diff --git a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx index 5ca718d01f493..ad25f7af40974 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` diff --git a/src/content/docs/en/guides/integrations-guide/netlify.mdx b/src/content/docs/en/guides/integrations-guide/netlify.mdx index 7cd84245495bf..92aaf98279218 100644 --- a/src/content/docs/en/guides/integrations-guide/netlify.mdx +++ b/src/content/docs/en/guides/integrations-guide/netlify.mdx @@ -67,28 +67,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 @@ -97,10 +80,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - excludeMiddleware: true, - }, + adapter: netlify({ + edgeMiddleware: true, + }), }); ``` @@ -146,10 +128,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - split: true, - }, + adapter: netlify({ + functionPerRoute: true, + }), }); ``` diff --git a/src/content/docs/en/guides/integrations-guide/node.mdx b/src/content/docs/en/guides/integrations-guide/node.mdx index bb864e82e5f2b..840eb4ddf37bd 100644 --- a/src/content/docs/en/guides/integrations-guide/node.mdx +++ b/src/content/docs/en/guides/integrations-guide/node.mdx @@ -172,7 +172,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..11f07bb6446fc 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. 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 c4757bc288efc..0a198045c8634 100644 --- a/src/content/docs/en/guides/integrations-guide/vercel.mdx +++ b/src/content/docs/en/guides/integrations-guide/vercel.mdx @@ -71,18 +71,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'; ``` @@ -105,7 +99,7 @@ To configure this adapter, pass an object to the `vercel()` function call in `as ### analytics **Type:** `boolean`<br/> -**Available for:** Serverless, Edge, Static<br/> +**Available for:** Serverless, Static<br/> **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. @@ -126,7 +120,7 @@ export default defineConfig({ ### imagesConfig **Type:** `VercelImageConfig`<br/> -**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. @@ -149,7 +143,7 @@ export default defineConfig({ ### imageService **Type:** `boolean`<br/> -**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. @@ -190,7 +184,7 @@ import astroLogo from '../assets/logo.png'; ### includeFiles **Type:** `string[]`<br/> -**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. @@ -207,10 +201,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[]`<br/> @@ -242,10 +232,9 @@ import vercel from '@astrojs/vercel/serverless'; export default defineConfig({ output: 'server', - adapter: vercel(), - build: { - split: true, - }, + adapter: vercel({ + functionPerRoute: true, + }), }); ``` @@ -284,7 +273,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 @@ -292,10 +281,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/reference/configuration-reference.mdx b/src/content/docs/en/reference/configuration-reference.mdx index 3fffc314686fe..acc60bf975943 100644 --- a/src/content/docs/en/reference/configuration-reference.mdx +++ b/src/content/docs/en/reference/configuration-reference.mdx @@ -197,15 +197,15 @@ Your final, deployed URL. Astro uses this full URL to generate your sitemap and <p> **Type:** `boolean`<br /> -**Default:** `false` +**Default:** `true` </p> -This is an option to minify your HTML output and reduce the size of your HTML files. When enabled, Astro removes all whitespace from your HTML, including line breaks, from `.astro` components. This occurs both in development mode and in the final build. -To enable this, set the `compressHTML` flag to `true`. +This is an option to minify your HTML output and reduce the size of your HTML files. By default, Astro removes all whitespace from your HTML, including line breaks, from `.astro` components. This occurs both in development mode and in the final build. +To disable HTML compression, set the `compressHTML` flag to `false`. ```js { - compressHTML: true + compressHTML: false } ``` @@ -229,12 +229,7 @@ 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`. -By default, the value of `import.meta.env.BASE_URL` includes a trailing slash. If you have the [`trailingSlash`](/en/reference/configuration-reference/#trailingslash) option set to `'never'`, you will need to add it manually in your static asset imports and URLs. - -```astro -<a href="/docs/about/">About</a> -<img src=`${import.meta.env.BASE_URL}image.png`> -``` +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. ### trailingSlash @@ -268,17 +263,19 @@ You can also set this if you prefer to be more strict yourself, so that URLs wit <p> -**Type:** `'where' | 'class'`<br /> -**Default:** `'where'`<br /> +**Type:** `'where' | 'class' | 'attribute'`<br /> +**Default:** `'attribute'`<br /> <Since v="2.4" /> </p> Specify the strategy used for scoping styles within Astro components. Choose from: - - `'where'` - Use `:where` selectors, causing no specifity increase. - - `'class'` - Use class-based selectors, causing a +1 specifity increase. + - `'where'` - Use `:where` selectors, causing no specifity increase. + - `'class'` - Use class-based selectors, causing a +1 specifity increase. + - `'attribute'` - Use `data-` attributes, causing no specifity increase. Using `'class'` is helpful when you want to ensure that element selectors within an Astro component override global style defaults (e.g. from a global stylesheet). Using `'where'` gives you more control over specifity, but requires that you use higher-specifity 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 @@ -508,7 +505,7 @@ configuration files for redirects and do not need/want HTML based redirects. <p> **Type:** `'always' | 'auto' | 'never'`<br /> -**Default:** `never`<br /> +**Default:** `auto`<br /> <Since v="2.6.0" /> </p> @@ -520,7 +517,7 @@ Control whether project styles are sent to the browser in a separate css file or ```js { build: { - inlineStylesheets: `auto`, + inlineStylesheets: `never`, }, } ``` @@ -531,24 +528,12 @@ Control whether project styles are sent to the browser in a separate css file or <p> **Type:** `boolean`<br /> -**Default:** `false`<br /> -<Since v="2.7.0" /> +**Default:** `false` </p> -Defines how the SSR code should be bundled when built. +The build config option `build.split` has been replaced by the adapter configuration option [`functionPerRoute`](/en/reference/adapter-reference/#functionperroute). -When `split` is `true`, Astro will emit a file for each page. -Each file emitted will render only one page. The pages will be emitted -inside a `dist/pages/` directory, and the emitted files will keep the same file paths -of the `src/pages` directory. - -```js -{ - build: { - split: true - } -} -``` +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 @@ -556,21 +541,12 @@ of the `src/pages` directory. <p> **Type:** `boolean`<br /> -**Default:** `false`<br /> -<Since v="2.8.0" /> +**Default:** `false` </p> -Defines whether or not any SSR middleware code will be bundled when built. +The build config option `build.excludeMiddleware` has been replaced by the adapter configuration option [`edgeMiddleware`](/en/reference/adapter-reference/#edgemiddleware). -When enabled, middleware code is not bundled and imported by all pages during the build. To instead execute and import middleware code manually, set `build.excludeMiddleware: true`: - -```js -{ - build: { - excludeMiddleware: true - } -} -``` +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. ## Server Options @@ -588,7 +564,7 @@ To set different configuration based on the command run ("dev", "preview") a fun ```js { // Example: Use the function syntax to customize based on command - server: ({ command }) => ({ port: command === 'dev' ? 3000 : 4000 }) + server: ({ command }) => ({ port: command === 'dev' ? 4321 : 4000 }) } ``` @@ -612,7 +588,7 @@ Set which network IP addresses the server should listen on (i.e. non-localhost I <p> **Type:** `number`<br /> -**Default:** `3000` +**Default:** `4321` </p> Set which port the server should listen on. @@ -645,7 +621,7 @@ Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. <p> **Type:** `Object`<br /> -**Default:** `{entrypoint: 'astro/assets/services/squoosh', config?: {}}`<br /> +**Default:** `{entrypoint: 'astro/assets/services/sharp', config?: {}}`<br /> <Since v="2.1.0" /> </p> @@ -884,7 +860,7 @@ 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 and Turbolinks). +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). Read our [Integrations Guide](/en/guides/integrations-guide/) for help getting started with Astro Integrations. @@ -936,28 +912,6 @@ in the latest version, so that you can continue to upgrade and take advantage of Astro offers experimental flags to give users early access to new features. These flags are not guaranteed to be stable. -### experimental.assets - -<p> - -**Type:** `boolean`<br /> -**Default:** `false`<br /> -<Since v="2.1.0" /> -</p> - -Enable experimental support for optimizing and resizing images. With this enabled, a new `astro:assets` module will be exposed. - -To enable this feature, set `experimental.assets` to `true` in your Astro config: - -```js -{ - experimental: { - assets: true, - }, -} -``` - - ### experimental.viewTransitions <p> diff --git a/src/content/docs/en/reference/error-reference.mdx b/src/content/docs/en/reference/error-reference.mdx index 029f00b2346f2..02b2b1e9124f6 100644 --- a/src/content/docs/en/reference/error-reference.mdx +++ b/src/content/docs/en/reference/error-reference.mdx @@ -57,6 +57,7 @@ The following reference is a complete list of the errors you may encounter while - [**AstroGlobNoMatch**](/en/reference/errors/astro-glob-no-match/)<br/>Astro.glob() did not match any files. - [**RedirectWithNoLocation**](/en/reference/errors/redirect-with-no-location/)<br/>A redirect must be given a location with the `Location` header. - [**InvalidDynamicRoute**](/en/reference/errors/invalid-dynamic-route/)<br/>Invalid dynamic route. +- [**MissingSharp**](/en/reference/errors/missing-sharp/)<br/>Could not find Sharp. - [**UnknownViteError**](/en/reference/errors/unknown-vite-error/)<br/>Unknown Vite Error. - [**FailedToLoadModuleSSR**](/en/reference/errors/failed-to-load-module-ssr/)<br/>Could not import file. - [**InvalidGlob**](/en/reference/errors/invalid-glob/)<br/>Invalid glob pattern. diff --git a/src/content/docs/en/reference/errors/expected-image-options.mdx b/src/content/docs/en/reference/errors/expected-image-options.mdx index 10557b0aac826..adf440185d160 100644 --- a/src/content/docs/en/reference/errors/expected-image-options.mdx +++ b/src/content/docs/en/reference/errors/expected-image-options.mdx @@ -28,6 +28,6 @@ const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); In most cases, this error happens because parameters were passed directly instead of inside an object. **See Also:** -- [Assets (Experimental)](/en/guides/assets/) +- [Images](/en/guides/images/) diff --git a/src/content/docs/en/reference/errors/expected-image.mdx b/src/content/docs/en/reference/errors/expected-image.mdx index 6060dae8ce657..bd8e779190a6c 100644 --- a/src/content/docs/en/reference/errors/expected-image.mdx +++ b/src/content/docs/en/reference/errors/expected-image.mdx @@ -31,6 +31,6 @@ import myImage from "../assets/my_image.png"; In most cases, this error happens when the value passed to `src` is undefined. **See Also:** -- [Assets (Experimental)](/en/guides/assets/) +- [Images](/en/guides/images/) diff --git a/src/content/docs/en/reference/errors/image-missing-alt.mdx b/src/content/docs/en/reference/errors/image-missing-alt.mdx index 2ea961340f5f2..3d01cd92a9979 100644 --- a/src/content/docs/en/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/en/reference/errors/image-missing-alt.mdx @@ -21,8 +21,8 @@ The `alt` property allows you to provide descriptive alt text to users of screen 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. **See Also:** -- [Assets (Experimental)](/en/guides/assets/) -- [Image component](/en/guides/assets/#image--astroassets) --  [Image component#alt](/en/guides/assets/#alt-required) +- [Images](/en/guides/images/) +- [Image component](/en/guides/images/#image--astroassets) +-  [Image component#alt](/en/guides/images/#alt-required) diff --git a/src/content/docs/en/reference/errors/local-image-used-wrongly.mdx b/src/content/docs/en/reference/errors/local-image-used-wrongly.mdx index 1f697ac9ec76a..99574a8cc1ff2 100644 --- a/src/content/docs/en/reference/errors/local-image-used-wrongly.mdx +++ b/src/content/docs/en/reference/errors/local-image-used-wrongly.mdx @@ -32,6 +32,6 @@ import myImage from "../my_image.png"; ``` **See Also:** -- [Assets (Experimental)](/en/guides/assets/) +- [Images](/en/guides/images/) diff --git a/src/content/docs/en/reference/errors/locals-not-an-object.mdx b/src/content/docs/en/reference/errors/locals-not-an-object.mdx index d503a11695d32..c4ca3a1992415 100644 --- a/src/content/docs/en/reference/errors/locals-not-an-object.mdx +++ b/src/content/docs/en/reference/errors/locals-not-an-object.mdx @@ -20,7 +20,7 @@ Thrown in development mode when `locals` is overwritten with something that is n For example: ```ts -import {defineMiddleware} from "astro/middleware"; +import {defineMiddleware} from "astro:middleware"; export const onRequest = defineMiddleware((context, next) => { context.locals = 1541; return next(); diff --git a/src/content/docs/en/reference/errors/markdown-image-not-found.mdx b/src/content/docs/en/reference/errors/markdown-image-not-found.mdx index 1450d5cd79023..6feeea6e2f75d 100644 --- a/src/content/docs/en/reference/errors/markdown-image-not-found.mdx +++ b/src/content/docs/en/reference/errors/markdown-image-not-found.mdx @@ -21,6 +21,6 @@ Astro could not find an image you included in your Markdown content. Usually, th Images in Markdown are relative to the current file. To refer to an image that is located in the same folder as the `.md` file, the path should start with `./` **See Also:** -- [Assets (Experimental)](/en/guides/assets/) +- [Images](/en/guides/images/) diff --git a/src/content/docs/en/reference/errors/middleware-no-data-or-next-called.mdx b/src/content/docs/en/reference/errors/middleware-no-data-or-next-called.mdx index ba8e6ab5d6f9c..a469882ba3d49 100644 --- a/src/content/docs/en/reference/errors/middleware-no-data-or-next-called.mdx +++ b/src/content/docs/en/reference/errors/middleware-no-data-or-next-called.mdx @@ -20,7 +20,7 @@ Thrown when the middleware does not return any data or call the `next` function. For example: ```ts -import {defineMiddleware} from "astro/middleware"; +import {defineMiddleware} from "astro:middleware"; export const onRequest = defineMiddleware((context, _) => { // doesn't return anything or call `next` context.locals.someData = false; diff --git a/src/content/docs/en/reference/errors/middleware-not-aresponse.mdx b/src/content/docs/en/reference/errors/middleware-not-aresponse.mdx index 92d6caac3f08f..a3a19a357841d 100644 --- a/src/content/docs/en/reference/errors/middleware-not-aresponse.mdx +++ b/src/content/docs/en/reference/errors/middleware-not-aresponse.mdx @@ -20,7 +20,7 @@ Thrown in development mode when middleware returns something that is not a `Resp For example: ```ts -import {defineMiddleware} from "astro/middleware"; +import {defineMiddleware} from "astro:middleware"; export const onRequest = defineMiddleware(() => { return "string" }); diff --git a/src/content/docs/en/reference/errors/missing-image-dimension.mdx b/src/content/docs/en/reference/errors/missing-image-dimension.mdx index f960c46d62260..82ef85cdfa59c 100644 --- a/src/content/docs/en/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/en/reference/errors/missing-image-dimension.mdx @@ -21,7 +21,7 @@ For remote images, `width` and `height` cannot be inferred from the original fil If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](/en/guides/imports/#other-assets). **See Also:** -- [Assets (Experimental)](/en/guides/assets/) -- [Image component#width-and-height](/en/guides/assets/#width-and-height) +- [Images](/en/guides/images/) +- [Image component#width-and-height-required](/en/guides/images/#width-and-height-required-for-public-and-remote-images) diff --git a/src/content/docs/en/reference/errors/missing-sharp.mdx b/src/content/docs/en/reference/errors/missing-sharp.mdx new file mode 100644 index 0000000000000..b4f82b5fd16e6 --- /dev/null +++ b/src/content/docs/en/reference/errors/missing-sharp.mdx @@ -0,0 +1,37 @@ +--- +# NOTE: This file is auto-generated from 'scripts/error-docgen.mjs' +# Do not make edits to it directly, they will be overwritten. +# Instead, change this file: https://github.com/withastro/astro/blob/main/packages/astro/src/core/errors/errors-data.ts +# Translators, please remove this note and the <DontEditWarning/> component. + +title: Could not find Sharp. +i18nReady: true +githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/errors/errors-data.ts +--- +import DontEditWarning from '~/components/DontEditWarning.astro' + +<DontEditWarning /> + + +> **MissingSharp**: Could not find Sharp. Please install Sharp (`sharp`) manually into your project. + +## What went wrong? +Sharp is the default image service used for `astro:assets`. When using a [strict package manager](https://pnpm.io/pnpm-vs-npm#npms-flat-tree) like pnpm, Sharp must be installed manually into your project in order to use image processing. + +If you are not using `astro:assets` for image processing, and do not wish to install Sharp, you can configure the following passthrough image service that does no processing: + +```js +import { defineConfig, passthroughImageService } from "astro/config"; +export default defineConfig({ + image: { + service: passthroughImageService(), + }, +}); +``` + +**See Also:** +- [Default Image Service](/en/guides/images/#default-image-service) +- [Image Component](/en/guides/images/#image--astroassets) +- [Image Services API](/en/reference/image-service-reference/) + + 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 b30085753a7aa..33cea00ba861d 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 @@ -14,7 +14,7 @@ import DontEditWarning from '~/components/DontEditWarning.astro' :::caution[Deprecated] -since version 2.6 +Deprecated since version 2.6. ::: > **StaticRedirectNotAvailable**: Redirects are only available when using `output: 'server'` or `output: 'hybrid'`. Update your Astro config if you need SSR features. diff --git a/src/content/docs/en/reference/errors/unsupported-image-format.mdx b/src/content/docs/en/reference/errors/unsupported-image-format.mdx index 0d32e659dedfb..3c9632ef66bed 100644 --- a/src/content/docs/en/reference/errors/unsupported-image-format.mdx +++ b/src/content/docs/en/reference/errors/unsupported-image-format.mdx @@ -18,10 +18,10 @@ import DontEditWarning from '~/components/DontEditWarning.astro' ## What went wrong? The built-in image services do not currently support optimizing all image formats. -For unsupported formats such as SVGs and GIFs, you may be able to use an `img` tag directly: +For unsupported formats such as GIFs, you may be able to use an `img` tag directly: ```astro --- -import rocket from '../assets/images/rocket.svg'; +import rocket from '../assets/images/rocket.gif'; --- <img src={rocket.src} width={rocket.width} height={rocket.height} alt="A rocketship in space." /> From 76ab7f0df4aeda7f6967aa7ce26963343b8a7eaf Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 13:14:53 +0000 Subject: [PATCH 060/119] deleting es/guides/assets --- src/content/docs/es/guides/assets.mdx | 375 -------------------------- 1 file changed, 375 deletions(-) delete mode 100644 src/content/docs/es/guides/assets.mdx diff --git a/src/content/docs/es/guides/assets.mdx b/src/content/docs/es/guides/assets.mdx deleted file mode 100644 index 4b15f9edd3b5d..0000000000000 --- a/src/content/docs/es/guides/assets.mdx +++ /dev/null @@ -1,375 +0,0 @@ ---- -title: Assets (Experimental) -description: Aprende como habilitar el soporte experimental de assets en Astro -i18nReady: false ---- -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -**Optimización para utilizar assets** está habilitado en Astro detras de una flag experimental. Esta funcionalidad reemplazará la integración opcional `@astrojs/image` - -La nueva experiencia usando assets se conforma por: -- Un nuevo componente interno `<Image />` -- Imágenes con optimizaciones automáticas en Markdown, [MDX](/es/guides/integrations-guide/mdx/) y [Markdoc](/es/guides/integrations-guide/markdoc/) -- Integración con colecciones de contenido -- Mejoras en los mensajes de error y los tipos - - -:::caution -Assets es una funcionalidad experimental de Astro introducida en v2.1. Esta API pudiese cambiar antes de ser parte de las funcionalidades marcadas como estables. -::: - -## Como habilitar Assets en tu Proyecto - -Habilitar assets incluye algunos cambios importantes en tu proyecto, pudiese ser requeridos algunos cambios manuales para aprovechar las nuevas funcionalidades. - -¡Se recomienda seguir todas las secciones de esta página para evitar errores y para aprovechar al máximo utilizando los assets como opción experimental! - -### Actualizar la Configuración - -Para habilitar assets -Agrega las siguientes líneas a tu archivo de configuración `astro.config.mjs` para habilitar el soporte de assets en tu proyecto - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from 'astro/config' - -export default defineConfig({ - experimental: { - assets: true - } -}); -``` - -La siguiente vez que ejecutes Astro, este va a actualizar tu archivo `src/env.d.ts` para configurar los tipos por ti. Para hacer eso de forma manual, reemplaza la referencia `astro/client` con `astro/client-image`: - -```ts title="src/env.d.ts" del={1} ins={2} -/// <reference types="astro/client" /> -/// <reference types="astro/client-image" /> -``` - -### Mueve tus imágenes a `src/assets/` - -Crea el directorio `src/assets/`, Astro lo reconocerá como tu carpeta de assets - -Recomendamos que guardes todas tus imágenes en el directorio `src/assets/`, de esta forma serán optimizadas y se podrá usar el alias oficial `~/assets`, sin embargo, esta ruta es opcional. Si no sabes donde colocar tus imágenes, o estás creando un producto al rededor de Astro (por ejemplo, un CMS), puedes colocar tus imágenes ahí y te prometemos que no las vamos a romper! Las imágenes pueden ser almacenadas en cualquier lugar, incluyendo junto con tu contenido, si así lo prefieres. - -Tus imágenes pueden ser usadas en archivos Markdown y por componentes (`.astro`, `.mdx`, y otros frameworks). - -### Actualiza las etiquetas `<img>` existentes - -Anteriormente, al importar una imagen esta retornaría un simple `string` con la ruta de la imagen. Con la nueva funcionalidad `image` habilitada, imágenes importadas como assets ahora corresponden a la siguiente interfaz: - -```ts -interface ImageMetadata { - src: string; - width: number; - height: number; - format: string; -} -``` - -Deberás actualizar el atributo `src` de cualquier etiqueta `<img>` existente, pudieses también actualizar otros atributos que ahora están habilitados desde de la imagen importada - -```astro title="src/components/MiComponente.astro" ".src" ".width" ".height" del={2,5} ins={3,6} ---- -import rocket from '../images/rocket.svg'; -import rocket from '../assets/images/rocket.svg'; ---- - -<img src={rocket} width="250" height="250" alt="Un cohete en el espacio." /> -<img src={rocket.src} width={rocket.width} height={rocket.height} alt="Un cohete en el espacio." /> -``` - -### Actualiza tus archivos Markdown, MDX y Markdoc - -Imágenes relativas ahora pueden ser referenciadas en archivos Markdown, MDX, Markdoc. Estas serán optimizadas y serializadas automáticamente por el proceso de build de Astro. - -Esto te permitirá mover tus imágenes del directorio `public/` para la nueva ruta reservada `src/assets/` o podrás moverlas cerca de tus archivos Markdown, MDX o Markdoc. (Puedes ver la ruta URL de estas imágenes que pasaron por el proceso de build en el ejemplo de abajo). - -Tus imágenes remotas y las existentes en `public/` seguirán siendo válidas pero no serán optimizadas automáticamente por el proceso de build de Astro. - -```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/" -# Mi Pagina Markdown - -<!-- Imagen local guardada en src/assets/stars.png --> -![Una noche llena de estrellas.](../../assets/stars.png) -<img src="/_astro/stars.hash.png" alt="Una noche llena de estrellas."> - -<!-- Imagen guardada en public/images/stars.png --> -![Una noche llena de estrellas.](/images/stars.png) -<img src="/images/stars.png" alt="Una noche llena de estrellas."> - -<!-- Imagen remota desde algún otro servidor --> -![Logo de Astro](https://docs.astro.build/assets/logomark-light.png) -<img src="https://docs.astro.build/assets/logomark-light.png" width="25" alt="Logo de Astro"> -``` - -### Dejar de usar `@astrojs/image` - -**Soporte interno para assets es incompatible con la integración `@astrojs/image`.** - -:::note[cortando imágenes] -La API de assets no soporta cortar imágenes. El comportamiento actual cambiará el tamaño de las imágenes para que encajen - -Usa la integración `@astrojs/image` si necesitas cortar imágenes. Si quieres lograr un resultado similar como alternativa puedes usar [la propiedad CSS `object-fit`](https://developer.mozilla.org/es/docs/Web/CSS/object-fit) -::: - -Para evitar errores en tu proyecto, completa los siguientes pasos: - -1. Elimina la integración `@astrojs/image`. - - Deberás [eliminar la integración](/es/guides/integrations-guide/#eliminando-una-integración) desisntalandola y quitandola de tu archivo `astro.config.mjs`. - -2. Migra cualquier componente `<Image />` existente. - - Cambia todos los `import` de `@astrojs/image/components` a `astro:assets` para usar el nuevo componente interno `<Image />`. - - Elimina cualquier atributo en los componentes que no sean [soportados en este momento por las propiedades para imágenes como assets](#propiedades). - - Por ejemplo, `aspectRatio` ya no es soportado, ya que, ahora es inferido automaticamente usando los atributos `width` and `height`. - - ```astro title="src/components/MiComponente.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"; - --- - - <Image - src={localImage} - width={300} - aspectRatio="16:9" - alt={localAlt} - /> - ``` - -3. Elimina todos los componentes `<Picture />` - - Por el momento, la funcionalidad para utilizar assets no incluye al componente `<Picture />` - - En su lugar, puedes usar los atributos para imágenes de HTML `srcset` y `sizes`, sino también puedes usar la etiqueta `<picture>` [para dirección de arte o para crear imágenes responsivas](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction). - - -### Actualiza los schemas de las colecciones de contenido - -Ahora puedes declarar imágenes en tu frontmatter usando su ruta relativa con la carpeta actual. - -```md title="src/content/blog/mi-post.md" ---- -title: "Mi primera publicación para mi blog" -cover: "./firstpostcover.jpeg" # se interpretará como "src/content/blog/firstblogcover.jpeg" -coverAlt: "Una imagen de un atardecer detras de una cordillera" ---- - -Esto es un post para un blog -``` - -El nuevo helper `image` para colecciones de contenido te permite usar Zod para validar la metadata de la imagen. - -```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: "!La imagen de portada debe tener al menos 1080 pixeles de ancho!", - }), - coverAlt: z.string() - }) -}) - -export const collections = { - blog: blogCollection -}; -``` - -La imagen será importada y transformada en metadata que sea válida con la firma de imágenes importadas, permitiéndote pasarla como `src` a `<Image/>` o `getImage()`. El índice de una pagina de blog puede renderizar la imagen de portada y título de cada post del blog: - -```astro title="src/pages/blog.astro" {10} ---- -import { Image } from "astro:assets"; -import { getCollection } from "astro:content"; -import allBlogPosts = await getCollection("blog"); ---- - -{ - allBlogPosts.map((post) => ( - <div> - <Image src={post.data.cover} alt={post.data.coverAlt} /> - <h2> - <a hrf={`/blog/${post.slug}`}>{post.data.title}</a> - </h2> - </div> - )) -} -``` - -## Modulo `astro:assets` - -Habilitando el soporte para assets te permite acceder al módulo `astro:assets`. Este módulo expone las siguientes funcionalidades: - -- `<Image />` (disponible en archivos `.astro` y `.mdx`) -- `getImage()` (disponible en archivos `.astro` y `.mdx`) - -:::caution -`<Image />` es un componente de Astro que [no puede ser usado en componentes de otros frameworks](/es/core-concepts/framework-components/#puedo-usar-componentes-de-astro-dentro-de-mis-componentes-de-framework). - -`getImage()` depende de APIs que se ejecutan solo en el servidor y rompe el build cuando se usa del lado del cliente -::: - -### `<Image />` (`astro:assets`) - -El componente `<Image />` genera una etiqueta `<img>`. - -Este componente puede transformar las dimensiones, tipo de archivo y calidad de una imagen, creando así una imagen optimizada. La etiqueta `<img>` generada incluirá los atributos `width` (ancho) y `height` (altura) correctos para evitar movimientos inesperados en el layout **(Cumulative Layout Shift)**. - -:::tip[¿Qué es Cumulative Layout Shift?] -CLS es una puntuación que refleja que tanto contenido cambio de posición mientras cargaba la página. Lo ideal es que la puntuación CLS esté tan cerca de cero como sea posible, el componente `<Image />` ayuda a lograrlo seleccionando automaticamente los valores correctos para los atributos `width` y `height` en las imágenes locales. -::: - -Importa imágenes desde una **ruta de archivos relativa** o un alias [para imports](/es/guides/aliases/) en cualquier componente y luego usa el import como el atributo `src` del componente `<Image />`. - -```astro ---- -import { Image } from "astro:assets"; -import miImagen from "../assets/mi_imagen.png"; // La resolución de la imagen es 1600x900 ---- - -<!-- `alt` es un atributo obligatorio en el componente Image --> -<Image src={miImagen} alt="Una descripción para mi imagen." /> -``` - -```astro -<!-- Resultado --> -<!-- La imagen está optimizada y se asignan los atributos correctos --> -<img - src="/_astro/mi_imagen.hash.webp" - width="1600" - height="900" - decoding="async" - loading="lazy" - alt="Una descripción para mi imagen." -/> -``` - -### Propiedades - -#### `width` y `height` - -Estas propiedades definen las dimensiones que serán usadas por la imagen. - -Cuando son usadas imágenes locales con su relación de aspecto original, `width` y `height` pueden ser opcionales e inferidas automáticamente por el archivo fuente. Sin embargo, ambas propiedades son requeridas por imágenes remotas. - -#### Formato - -De forma opcional puedes assignar el [tipo de archivo de la imagen](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types). El tipo de archivo usado por defecto es `webp`. - -#### `quality` - -`quality` es una propiedad opcional que puede ser: -- un valor predeterminado (`low`, `mid`, `high`, `max`) que es normalizado automaticamente entre formatos. -- un numero del `0` al `100` (su interpretación es distinta entre formatos). - -##### `alt` (requerido) - -Usa el atributo `alt` para asignar un [texto alt descriptivo](https://www.w3.org/WAI/tutorials/images/) para imágenes. - -Este atributo es requerido por el componente `<Image />`. Este componente arrojará un error si no se proporciona un texto para alt - -Si la imagen es meramente decorativa (por ejemplo, no contribuye al entendimiento de la página), asigna `alt=""` al componente `<Image />` para que los lectores de pantallas sepan que deberán ignorar esa imagen. - -#### Propiedades adicionales - -Aparte de las propiedades ya mostradas, el componente `<Image />` acepta todas las demás propiedades aceptadas por la etiqueta HTML`<img>`. - -Por ejemplo, puedes proporcionar un `class` a la etiqueta `img` final. - -```astro ---- -import { Image } from "astro:assets"; -import MiImagen from "../assets/mi_imagen.png"; ---- - -<!-- `alt` es obligatorio en el componente Image --> -<Image src={myImage} alt="" class="mi-clase" /> -``` - -```astro -<!-- Resultado --> -<img - src="/_astro/mi_imagen.hash.webp" - width="1600" - height="900" - decoding="async" - loading="lazy" - class="mi-clase" - alt="" -/> -``` - -### `getImage()` (`astro:assets`) - -La intención de esta función es generar imágenes destinadas a ser usadas en algún otro lugar que no sea directamente en el HTML, por ejemplo una [Ruta de API](/es/core-concepts/endpoints/#endpoints-del-servidor-rutas-de-api) - -`getImage()` toma un objeto options con las mismas propiedades que el componente `<Image />` (excepto `alt`). - -```astro ---- -import { getImage } from "astro:assets"; -import miBackground from "../background.png" - -const optimizedBackground = await getImage({src: miBackground, format: 'avif'}) ---- - -<div style={`background-image: url(${optimizedBackground.src});`}></div> -``` - -Retornará un objeto con las siguientes propiedades: - -```js -{ - options: {...} // Parámetros que fueron pasados originalmente - src: "https://..." // Ruta para la imagen generada - attributes: {...} // Atributos HTML adicionales necesarios para renderizar la imagen (width, height, style, etc..) -} -``` - -## Usando sharp - -Astro usa [Squoosh](https://github.com/GoogleChromeLabs/squoosh) por defecto para transformar tus imágenes. Esto soporta todos los entornos de Javascript. - -Si estás deployando un entorno Node, es probable que quieras usar [sharp](https://github.com/lovell/sharp), el cual ofrece mejor performance pero Node es requerido. Para usar `sharp`, primero hay que instalarlo: - -<PackageManagerTabs> - <Fragment slot="npm"> - ```shell - npm install sharp - ``` - </Fragment> - <Fragment slot="pnpm"> - ```shell - pnpm install sharp - ``` - </Fragment> - <Fragment slot="yarn"> - ```shell - yarn add sharp - ``` - </Fragment> -</PackageManagerTabs> - -Luego, habilita el service `sharp` de Astro para imágenes en tu config: - -```js title="astro.config.mjs" -import { defineConfig, sharpImageService } from "astro/config"; - -export default defineConfig({ - experimental: { - assets: true, - }, - image: { - service: sharpImageService(), - }, -}) -``` From e7706e1e3ea768011524a02504c2820a7253eb15 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 13:18:27 +0000 Subject: [PATCH 061/119] deleted guides/assets from nav.ts files that had it --- src/i18n/es/nav.ts | 1 - src/i18n/it/nav.ts | 1 - src/i18n/ja/nav.ts | 1 - src/i18n/pt-br/nav.ts | 1 - src/i18n/ru/nav.ts | 1 - src/i18n/zh-cn/nav.ts | 1 - 6 files changed, 6 deletions(-) diff --git a/src/i18n/es/nav.ts b/src/i18n/es/nav.ts index 8b2dab821a670..5438861932f00 100644 --- a/src/i18n/es/nav.ts +++ b/src/i18n/es/nav.ts @@ -38,7 +38,6 @@ export default NavDictionary({ 'guides/content-collections': 'Colecciones de Contenido', 'guides/client-side-scripts': 'Scripts y Manejo de Eventos', 'guides/styling': 'Estilos y CSS', - 'guides/assets': 'Assets (Experimental)', 'guides/images': 'Imágenes', 'guides/fonts': 'Fuentes', 'guides/imports': 'Importaciones', diff --git a/src/i18n/it/nav.ts b/src/i18n/it/nav.ts index 56c0eb76bc081..8167b811c9ef5 100644 --- a/src/i18n/it/nav.ts +++ b/src/i18n/it/nav.ts @@ -38,7 +38,6 @@ export default NavDictionary({ 'guides/content-collections': 'Collezioni di Contenuti', 'guides/client-side-scripts': 'Script & Gestione degli Eventi', 'guides/styling': 'CSS & Stili', - 'guides/assets': 'Asset (Sperimentale)', 'guides/images': 'Immagini', 'guides/fonts': 'Font', 'guides/imports': 'Import', diff --git a/src/i18n/ja/nav.ts b/src/i18n/ja/nav.ts index 97676bd1e6cdc..ed506ad768311 100644 --- a/src/i18n/ja/nav.ts +++ b/src/i18n/ja/nav.ts @@ -44,7 +44,6 @@ export default NavDictionary({ 'guides/content-collections': 'コンテンツコレクション', 'guides/client-side-scripts': 'スクリプトとイベントハンドリング', 'guides/styling': 'CSSとスタイル', - 'guides/assets': 'アセット(実験的)', 'guides/images': '画像', 'guides/fonts': 'フォント', 'guides/imports': 'インポート', diff --git a/src/i18n/pt-br/nav.ts b/src/i18n/pt-br/nav.ts index 860c89e714495..0e2a986447f57 100644 --- a/src/i18n/pt-br/nav.ts +++ b/src/i18n/pt-br/nav.ts @@ -37,7 +37,6 @@ export default NavDictionary({ 'guides/content-collections': 'Coleções de Conteúdo', 'guides/client-side-scripts': 'Scripts & Manipulação de Eventos', 'guides/styling': 'Estilização e CSS', - 'guides/assets': 'Assets (Experimental)', 'guides/images': 'Imagens', 'guides/fonts': 'Fontes', 'guides/imports': 'Importações', diff --git a/src/i18n/ru/nav.ts b/src/i18n/ru/nav.ts index 17621f74d5ebc..b6385d627a950 100644 --- a/src/i18n/ru/nav.ts +++ b/src/i18n/ru/nav.ts @@ -57,6 +57,5 @@ export default NavDictionary({ examples: 'Рецепты', 'guides/recipes': 'Больше рецептов', 'guides/fonts': 'Шрифты', - 'guides/assets': 'Ресурсы (эксперим.)', 'core-concepts/astro-syntax': 'Синтаксис Astro', }); diff --git a/src/i18n/zh-cn/nav.ts b/src/i18n/zh-cn/nav.ts index cff94fe4d5b2a..c02a33b2c7524 100644 --- a/src/i18n/zh-cn/nav.ts +++ b/src/i18n/zh-cn/nav.ts @@ -38,7 +38,6 @@ export default NavDictionary({ 'guides/server-side-rendering': '服务端渲染 (SSR)', 'guides/client-side-scripts': '处理脚本和事件', 'guides/styling': 'CSS 样式', - 'guides/assets': '资源 (实验性)', 'guides/fonts': '字体', 'guides/images': '图像', 'guides/imports': '导入', From dea089e7e221696bb57c610a59f76057cecb3793 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Wed, 23 Aug 2023 13:24:12 +0000 Subject: [PATCH 062/119] remove mention of assets folder from project structure --- src/content/docs/en/core-concepts/project-structure.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/content/docs/en/core-concepts/project-structure.mdx b/src/content/docs/en/core-concepts/project-structure.mdx index 57d63aca83613..fada6522aac07 100644 --- a/src/content/docs/en/core-concepts/project-structure.mdx +++ b/src/content/docs/en/core-concepts/project-structure.mdx @@ -66,10 +66,6 @@ Some files (like Astro components) are not even sent to the browser as written b While this guide describes some popular conventions used in the Astro community, the only directories reserved by Astro are `src/pages/` and `src/content/`. You are free to rename and reorganize any other directories in a way that works best for you. ::: -### `src/assets` - -The [`src/assets`](/en/guides/assets/) directory is the recommended folder to use for storing assets (e.g. images) that are processed by Astro. This is not required, and this is not a special reserved folder. - ### `src/components` **Components** are reusable units of code for your HTML pages. These could be [Astro components](/en/core-concepts/astro-components/), or [UI framework components](/en/core-concepts/framework-components/) like React or Vue. It is common to group and organize all of your project components together in this folder. From 617eff8f60f7cf5f7c1eeefc5b09fca98892a835 Mon Sep 17 00:00:00 2001 From: Nate Moore <natemoo-re@users.noreply.github.com> Date: Wed, 23 Aug 2023 19:01:53 -0500 Subject: [PATCH 063/119] Update `class:list` and astro-hash classes (#4322) Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> --- src/content/docs/en/guides/styling.mdx | 6 +++--- src/content/docs/en/reference/directives-reference.mdx | 9 +++------ 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/content/docs/en/guides/styling.mdx b/src/content/docs/en/guides/styling.mdx index 85f325dcb42d4..45749caee2244 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,7 +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[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. diff --git a/src/content/docs/en/reference/directives-reference.mdx b/src/content/docs/en/reference/directives-reference.mdx index 74f11e4330e22..e9ac11aaccfb3 100644 --- a/src/content/docs/en/reference/directives-reference.mdx +++ b/src/content/docs/en/reference/directives-reference.mdx @@ -24,24 +24,21 @@ A template directive is never included directly in the final HTML output of a co ## Common Directives ### `class:list` -`class:list={...}` takes an array of class values and converts them into a class string. This is inspired by @lukeed's popular [clsx](https://github.com/lukeed/clsx) helper library, but built directly into Astro itself. +`class:list={...}` takes an array of class values and converts them into a class string. This is powered by @lukeed's popular [clsx](https://github.com/lukeed/clsx) helper library. `class:list` takes an array of several different possible value kinds: - `string`: Added to the element `class` - `Object`: All truthy keys are added to the element `class` - `Array`: flattened -- `Set`: flattened -- `false` or `null`: skipped +- `false`, `null`, or `undefined`: skipped ```astro <!-- This --> -<span class:list={[ 'hello goodbye', { hello: true, world: true }, new Set([ 'hello', 'friend' ]) ]} /> +<span class:list={[ 'hello goodbye', { world: true }, [ 'friend' ] ]} /> <!-- Becomes --> <span class="hello goodbye world friend"></span> ``` -Duplicate values are removed automatically. - ### `set:html` `set:html={string}` injects an HTML string into an element, similar to setting `el.innerHTML`. From c421b013bafc389e4d8c9f0c119753dde7bd6535 Mon Sep 17 00:00:00 2001 From: Bjorn Lu <bjornlu.dev@gmail.com> Date: Thu, 24 Aug 2023 23:48:34 +0800 Subject: [PATCH 064/119] Remove markdown draft reference (#4354) --- .../docs/en/guides/content-collections.mdx | 10 ++++ .../docs/en/guides/markdown-content.mdx | 56 +------------------ .../docs/en/reference/cli-reference.mdx | 18 +++--- 3 files changed, 18 insertions(+), 66 deletions(-) diff --git a/src/content/docs/en/guides/content-collections.mdx b/src/content/docs/en/guides/content-collections.mdx index 5997732577d05..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 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/reference/cli-reference.mdx b/src/content/docs/en/reference/cli-reference.mdx index 8ec7b2ccc255c..146982a266b6f 100644 --- a/src/content/docs/en/reference/cli-reference.mdx +++ b/src/content/docs/en/reference/cli-reference.mdx @@ -103,7 +103,7 @@ When you follow the instructions to [install Astro manually](/en/install/manual/ } ``` -You will often use these `astro` commands, or the scripts that run them, without any flags. Add flags to the command when you want to customize the command's behavior. For example, you may wish to start the development server on a different port, or build your site including draft pages. +You will often use these `astro` commands, or the scripts that run them, without any flags. Add flags to the command when you want to customize the command's behavior. For example, you may wish to start the development server on a different port, or build your site with verbose logs for debugging. <PackageManagerTabs> <Fragment slot="npm"> @@ -111,8 +111,8 @@ You will often use these `astro` commands, or the scripts that run them, without # run the dev server on port 8080 using the `start` script in `package.json` npm run start -- --port 8080 - # build your site including draft pages using the `build` script in `package.json` - npm run build -- --drafts + # build your site with verbose logs using the `build` script in `package.json` + npm run build -- --verbose ``` (The extra `--` before the `--port` flag is necessary for `npm` to pass your flags to the `astro` command.) </Fragment> @@ -121,8 +121,8 @@ You will often use these `astro` commands, or the scripts that run them, without # run the dev server on port 8080 using the `start` script in `package.json` pnpm start --port 8080 - # build your site including draft pages using the `build` script in `package.json` - pnpm build --drafts + # build your site with verbose logs using the `build` script in `package.json` + pnpm build --verbose ``` </Fragment> <Fragment slot="yarn"> @@ -130,8 +130,8 @@ You will often use these `astro` commands, or the scripts that run them, without # run the dev server on port 8080 using the `start` script in `package.json` yarn start --port 8080 - # build your site including draft pages using the `build` script in `package.json` - yarn build --drafts + # build your site with verbose logs using the `build` script in `package.json` + yarn build --verbose ``` </Fragment> </PackageManagerTabs> @@ -221,10 +221,6 @@ Builds your site for deployment. By default, this will generate static files and Use these flags to customize your build. For flags shared with other Astro commands, see [common flags](#common-flags) below. -#### `--drafts` - -Includes [Markdown draft pages](/en/guides/markdown-content/#draft-pages) in the build. - ## `astro preview` Starts a local server to serve your static `dist/` directory. From 108287a84104bf759c782f4de318f1c8921464e6 Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem <hello@elian.codes> Date: Fri, 25 Aug 2023 12:00:48 +0200 Subject: [PATCH 065/119] update endpoints --- .../docs/en/core-concepts/endpoints.mdx | 45 +++++++------------ 1 file changed, 17 insertions(+), 28 deletions(-) diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index f03e7cb7352cf..b7eed631fd4f4 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -18,12 +18,11 @@ Endpoints export a `get` function (optionally `async`) that receives a [context // Example: src/pages/builtwith.json.ts // Outputs: /builtwith.json export async function GET({params, request}) { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ name: 'Astro', - url: 'https://astro.build/', - }), - }; + url: 'https://astro.build/' + }) + ) } ``` @@ -32,11 +31,7 @@ The return object can also have an `encoding` property. It can be any valid [`Bu ```ts title="src/pages/astro-logo.png.ts" {6} export async function GET({ params, request }) { const response = await fetch("https://docs.astro.build/assets/full-logo-light.png"); - const buffer = Buffer.from(await response.arrayBuffer()); - return { - body: buffer, - encoding: 'binary', - }; + return new Response(await response.arrayBuffer()); } ``` @@ -45,8 +40,7 @@ You can also type your endpoint functions using the `APIRoute` type: ```ts import type { APIRoute } from 'astro'; -export const GET: APIRoute = async ({ params, request }) => { -... +export const GET: APIRoute = async ({ params, request }) => {...} ``` ### `params` and Dynamic routing @@ -85,11 +79,10 @@ All endpoints receive a `request` property, but in static mode, you only have ac import type { APIRoute } from 'astro'; export const GET: APIRoute = ({ params, request }) => { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ path: new URL(request.url).pathname }) - }; + ) } ``` @@ -150,35 +143,31 @@ You can also export an `ALL` function to match any method that doesn't have a co ```ts title="src/pages/methods.json.ts" export const GET: APIRoute = ({ params, request }) => { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ message: "This was a GET!" }) - } -}; + ) +} export const POST: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ message: "This was a POST!" }) - } + ) } export const DELETE: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ message: "This was a DELETE!" }) - } + ) } export const ALL: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ + return new Resonse(JSON.stringify({ message: `This was a ${request.method}!` }) - } + ) } ``` From 88d2195b4f80597572d9f080bff3268dcb25d656 Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem <hello@elian.codes> Date: Fri, 25 Aug 2023 14:42:25 +0200 Subject: [PATCH 066/119] update endpoints --- src/content/docs/en/core-concepts/endpoints.mdx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index b7eed631fd4f4..0fbf4d3b5dda2 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -54,14 +54,13 @@ const usernames = ["Sarah", "Chris", "Dan"] export const GET: APIRoute = ({ params, request }) => { const id = params.id; - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ name: usernames[id] }) - } -}; + ) +} -export function getStaticPaths () { +export function getStaticPaths() { return [ { params: { id: "0"} }, { params: { id: "1"} }, From d3af1a32d16b3266a7e7ddc8d18dc90c12b3ed1d Mon Sep 17 00:00:00 2001 From: Elian Van Cutsem <hello@elian.codes> Date: Fri, 25 Aug 2023 15:23:34 +0200 Subject: [PATCH 067/119] apply Blu's suggestions --- .../docs/en/core-concepts/endpoints.mdx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index 0fbf4d3b5dda2..5b173a98d999e 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -18,7 +18,8 @@ Endpoints export a `get` function (optionally `async`) that receives a [context // Example: src/pages/builtwith.json.ts // Outputs: /builtwith.json export async function GET({params, request}) { - return new Response(JSON.stringify({ + return new Response( + JSON.stringify({ name: 'Astro', url: 'https://astro.build/' }) @@ -54,7 +55,8 @@ const usernames = ["Sarah", "Chris", "Dan"] export const GET: APIRoute = ({ params, request }) => { const id = params.id; - return new Response(JSON.stringify({ + return new Response( + JSON.stringify({ name: usernames[id] }) ) @@ -112,12 +114,14 @@ export async function GET({ params }) { }); } - return new Response(JSON.stringify(product), { - status: 200, - headers: { - "Content-Type": "application/json" + return new Response( + JSON.stringify(product), { + status: 200, + headers: { + "Content-Type": "application/json" + } } - }); + ); } ``` From 07a353eab8b3099dbf355bf71d314122c2bda882 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Fri, 25 Aug 2023 14:50:21 +0000 Subject: [PATCH 068/119] clearer, and scarier unexperimental image assets --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index fb232bd550bba..1cca7a95badd0 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -64,7 +64,7 @@ export default defineConfig({ These features are now available by default: - [View Transitions](/en/guides/view-transitions/) for animated page transitions and persistent islands. -- A new image services API `astro:assets` for [using images in Astro](/en/guides/images/), including a new `<Image />` component and `getImage()` function. Please read the detailed [image upgrade advice](/en/guides/images/#upgrade-to-v30-from-v2x) to see how this might affect your project. +- 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! From 0297c6c90d7e91b13c3a18bfda33933469da9482 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger <sarah@rainsberger.ca> Date: Fri, 25 Aug 2023 12:04:47 -0300 Subject: [PATCH 069/119] translatable --- src/content/docs/en/guides/upgrade-to/v3.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 1cca7a95badd0..e9d500e69f554 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -1,7 +1,7 @@ --- title: Upgrade to Astro v3 -description: How to upgrade your project to the latest version of Astro. -i18nReady: false +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' From a91adb348a837dab03f1c254e3d6c083c24ec4bb Mon Sep 17 00:00:00 2001 From: Matthew Phillips <matthew@skypack.dev> Date: Fri, 25 Aug 2023 13:51:20 -0400 Subject: [PATCH 070/119] View transitions 3.0 changes (#4320) Co-authored-by: Nate Moore <natemoo-re@users.noreply.github.com> Co-authored-by: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> Co-authored-by: Matthew Phillips <matthew@skypack.dev> Co-authored-by: Nate Moore <nate@astro.build> Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> --- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- .../docs/en/guides/view-transitions.mdx | 215 ++++++++++++++---- src/i18n/en/nav.ts | 2 +- 3 files changed, 175 insertions(+), 44 deletions(-) diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index e9d500e69f554..2235ef259a995 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -63,7 +63,7 @@ export default defineConfig({ These features are now available by default: -- [View Transitions](/en/guides/view-transitions/) for animated page transitions and persistent islands. +- 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! 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