From 3f6abffa9e365ab50f64441d8681ff947da8a13a Mon Sep 17 00:00:00 2001 From: HakuRan Date: Mon, 1 Jun 2026 15:33:08 +0800 Subject: [PATCH 1/9] install --- .../guides/integrations-guide/cloudflare.mdx | 665 ++++++++++++++++++ 1 file changed, 665 insertions(+) create mode 100644 src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx new file mode 100644 index 0000000000000..cf6b7ec1148fb --- /dev/null +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -0,0 +1,665 @@ +--- +type: integration +title: '@astrojs/cloudflare' +description: 了解如何使用 @astrojs/cloudflare 适配器来部署 Astro 项目。 +sidebar: + label: Cloudflare +githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/integrations/cloudflare/' +category: adapter +i18nReady: true +--- + +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; +import ReadMore from '~/components/ReadMore.astro'; +import Since from '~/components/Since.astro'; +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; + +此适配器允许 Astro 将你的 [按需渲染路由及其功能](/zh-cn/guides/on-demand-rendering/) 部署到 [Cloudflare](https://www.cloudflare.com/),包括 [服务器群岛](/zh-cn/guides/server-islands/),[actions](/zh-cn/guides/actions/) 以及 [sessions](/zh-cn/guides/sessions/)。 + +如果你只是将 Astro 作为静态的站点构建器,则不需要适配器。 + +在我们的 [Cloudflare 部署指南](/zh-cn/guides/deploy/cloudflare/) 中学习如何部署你的 Astro 网站。 + +:::tip[更新到 Astro 6?] +Astro 6 需要将次适配器更新到 v13。 关于重大变更和迁移指南,请参阅 [针对 Astro 6 的 Cloudflare 适配器升级说明。](#upgrading-to-v13-and-astro-6) +::: + +## 为什么选择 Cloudflare? + +Cloudflare 的 [开发者平台](https://developers.cloudflare.com/) 能够让你开发全栈应用,并访问存储、AI 等资源,所有内容都部署到全球边缘网络上。该适配器会构建你的 Astro 项目,并通过 Cloudflare 进行部署。 + +## 安装 + +Astro 包含了一个 `astro add` 命令,用于自动设置官方集成。如果你愿意,也可以[手动安装集成](#手动安装)。 + +在 Astro 项目中使用 `asrto add` 命令添加 Cloudflare 适配器,以启用按需渲染。这将安装 `@astrojs/cloudflare` 并一步到位地对你的 `astro.config.mjs` 文件进行相应的更改。 + + + + ```sh + npx astro add cloudflare + ``` + + + ```sh + pnpm astro add cloudflare + ``` + + + ```sh + yarn astro add cloudflare + ``` + + +现在,你可以启用 [对每个页面的按需渲染](/zh-cn/guides/on-demand-rendering/#启用按需渲染),或者将你的构建输出配置设置为 `output: 'server'` 从而 [默认对所有页面都进行服务器端渲染](/zh-cn/guides/on-demand-rendering/#server-模式)。 + +### 手动安装 + + + +1. 使用适合你的包管理器将 `@astrojs/cloudflare` 适配器安装到你的项目依赖中 + + + + ```sh + npm install @astrojs/cloudflare + ``` + + + ```sh + pnpm add @astrojs/cloudflare + ``` + + + ```sh + yarn add @astrojs/cloudflare + ``` + + + +2. 将适配器添加到 `astro.config.*` 文件中: + + ```js title="astro.config.mjs" ins={2,5} + import { defineConfig } from 'astro/config'; + import cloudflare from '@astrojs/cloudflare'; + + export default defineConfig({ + adapter: cloudflare(), + }); + ``` +3. Astro 会自动生成默认配置,使用 package.json 中的 name 字段或目录名作为 Worker 名称。如果你需要自定义设置,可以手动创建 [Worker 配置文件](https://developers.cloudflare.com/workers/wrangler/configuration/)。以下示例声明了 KV 绑定: + + ```jsonc title="wrangler.jsonc" + { + "name": "my-astro-app", + // Add your bindings here, e.g.: + // "kv_namespaces": [{ "binding": "MY_KV", "id": "" }] + } + ``` + + +## Options + +The Cloudflare adapter accepts the following options from [`@cloudflare/vite-plugin`](https://developers.cloudflare.com/workers/vite-plugin/): + +- `auxiliaryWorkers` +- `configPath` +- `inspectorPort` +- `persistState` +- `remoteBindings` +- `experimental.headersAndRedirectsDevModeSupport` + +It also accepts the following: + +### `imageService` + +

+**Type:** `'passthrough' | 'cloudflare' | 'cloudflare-binding' | 'compile' | 'custom' | { build: 'compile', runtime?: 'cloudflare-binding' | 'passthrough' }`
+**Default:** `'cloudflare-binding'` +

+ +Determines which image service is used by the adapter. The adapter will default to `cloudflare-binding` mode when an incompatible image service is configured. Otherwise, it will use the globally configured image service: + +- **`cloudflare`:** Uses the [Cloudflare Image Resizing](https://developers.cloudflare.com/images/image-resizing/) service. +- **`cloudflare-binding`:** Uses the [Cloudflare Images binding](https://developers.cloudflare.com/images/transform-images/bindings/) for image transformation. The binding is automatically provisioned when you deploy. +- **`passthrough`:** Uses the existing [`noop`](/en/guides/images/#configure-no-op-passthrough-service) service. +- **`compile`:** Uses a combination of internal dependencies to transform images locally at build time for prerendered routes. The noop `passthrough` option is configured for on-demand rendered pages. +- **`custom`:** Always uses the image service configured in [Image Options](/en/reference/configuration-reference/#image-options). **This option will not check to see whether the configured image service works in Cloudflare's `workerd` runtime.** + +It is also possible to configure your image service as an object, setting both a build time and runtime service independently. Currently, `'compile'` is the only available build-time option. The supported runtime options are `'passthrough'` (default) and `'cloudflare-binding'`: + +```js title="astro.config.mjs" ins={6} +import { defineConfig } from 'astro/config'; +import cloudflare from '@astrojs/cloudflare'; + +export default defineConfig({ + adapter: cloudflare({ + imageService: { build: 'compile', runtime: 'cloudflare-binding' } + }), +}); +``` + +### `sessionKVBindingName` + +

+**Type:** `string`
+**Default:** `SESSION` + +

+ +Sets the name of the KV binding used for session storage. By default, the KV namespace is automatically provisioned when you deploy, and is named `SESSION`. You can change this name by setting the binding manually in your wrangler config. See [Sessions](#sessions) for more information. + +```js title="astro.config.mjs" "MY_SESSION_BINDING" +export default defineConfig({ + adapter: cloudflare({ + sessionKVBindingName: 'MY_SESSION_BINDING', + }), +}); +``` + +```jsonc title="wrangler.jsonc" +{ + "kv_namespaces": [ + { + "binding": "MY_SESSION_BINDING", + } + ] +} +``` + +### `imagesBindingName` + +

+**Type:** `string`
+**Default:** `IMAGES` +

+ +Sets the name of the Images binding used when [`imageService`](#imageservice) is set to `cloudflare-binding`. By default, the binding is automatically provisioned with the name `IMAGES` when you deploy. You can change it by setting the binding manually in your wrangler config: + +```js title="astro.config.mjs" "MY_IMAGES" +export default defineConfig({ + adapter: cloudflare({ + imageService: 'cloudflare-binding', + imagesBindingName: 'MY_IMAGES', + }), +}); +``` + +```jsonc title="wrangler.jsonc" +{ + "images": { + "binding": "MY_IMAGES" + } +} +``` + +### `prerenderEnvironment` + +

+**Type:** `'workerd' | 'node'`
+**Default:** `'workerd'` + +

+ +Controls which runtime is used for [prerendering](/en/guides/on-demand-rendering/) static pages at build time and during development. + +By default, prerendered pages are built using Cloudflare's `workerd` runtime to match the production environment as closely as possible. Set this option to `'node'` when your prerendered pages depend on Node.js APIs or NPM packages that are not compatible with `workerd`: + +```js title="astro.config.mjs" "prerenderEnvironment" +import { defineConfig } from 'astro/config'; +import cloudflare from '@astrojs/cloudflare'; + +export default defineConfig({ + adapter: cloudflare({ + prerenderEnvironment: 'node', + }), +}); +``` + +For example, if a prerendered page reads from the file system using `node:fs`, set `prerenderEnvironment` to `'node'`. On-demand rendered pages are unaffected by this option and always run in `workerd`. + +## Cloudflare runtime + +The Cloudflare runtime gives you access to environment variables, bindings to Cloudflare resources, and other Cloudflare-specific APIs. + +### Environment variables and bindings + +Environment variables and bindings are defined in your `wrangler.jsonc` configuration file. + + + +Define [environment variables](https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-wrangler) that do not store sensitive information in `wrangler.jsonc`: + +```jsonc title="wrangler.jsonc" +{ + "vars": { + "MY_VARIABLE": "test", + }, +} +``` + +[Secrets](https://developers.cloudflare.com/workers/configuration/secrets/) are a special type of environment variable that allow you to attach encrypted text values to your Worker. They need to be defined differently to ensure they are not visible within Wrangler or Cloudflare dashboard after you set them. + +To define `secrets`, add them through the [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) rather than in your Wrangler config file: + +```bash +npx wrangler secret put +``` + +To set secrets for local development, add a `.dev.vars` file to the root of the Astro project: + +```ini title=".dev.vars" +DB_PASSWORD=myPassword +``` + +Cloudflare environment variables and secrets can be imported from `"cloudflare:workers"`: + +```astro title="src/pages/index.astro" +--- +import { env } from 'cloudflare:workers'; + +const myVariable = env.MY_VARIABLE; +const myKVNamespace = env.MY_KV; +--- +``` + +They are also compatible with the [`astro:env` API](/en/guides/environment-variables/#type-safe-environment-variables): + +```js +import { MY_VARIABLE } from 'astro:env/server'; +``` + +See the [list of all supported bindings](https://developers.cloudflare.com/workers/wrangler/api/#supported-bindings) in the Cloudflare documentation. + +### The `cf` object + +The Cloudflare [`cf` object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties) contains request metadata such as geolocation information. Access it directly from the request: + +```astro title="src/pages/index.astro" +--- +const cf = Astro.request.cf; +const country = cf?.country; +--- +``` + +### Execution context + +Access the Cloudflare [`ExecutionContext`](https://developers.cloudflare.com/workers/runtime-apis/context/) through `Astro.locals.cfContext`. This is useful for operations like [`waitUntil()`](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil), or accessing [Durable Object exports](https://developers.cloudflare.com/workers/runtime-apis/context/#exports) within your page. + +```astro title="src/pages/index.astro" +--- +const cfContext = Astro.locals.cfContext; +cfContext.exports.Greeter.greet('Astro'); +cfContext.waitUntil(someAsyncOperation()); +--- +``` + +### Typing + +`wrangler` provides a [`types`](https://developers.cloudflare.com/workers/wrangler/commands/#types) command to generate TypeScript types for your bindings. This allows you to type your environment without the need for manual type definitions. + +Run `wrangler types` every time you change your configuration files (e.g. `wrangler.jsonc`, `.dev.vars`). + +:::note +The following example shows a script configuration to run `wrangler types` automatically before other commands: + +```json title="package.json" +{ + "scripts": { + "dev": "wrangler types && astro dev", + "start": "wrangler types && astro dev", + "build": "wrangler types && astro check && astro build", + "preview": "wrangler types && astro preview", + "astro": "astro" + } +} +``` + +::: + +## Cloudflare Platform + +### Headers + +Add [custom headers](https://developers.cloudflare.com/workers/static-assets/headers/) for static assets by creating a `_headers` file in your Astro project's `public/` folder. This file will be copied to the build output directory. Headers in `_headers` are not applied to responses generated by your Worker code. + +### Assets + +Assets built by Astro are all named with a hash and, therefore, can be given long cache headers. By default, Astro on Cloudflare will add such a header for these files. + +### Redirects + +Declare [custom redirects for static assets](https://developers.cloudflare.com/workers/static-assets/redirects/) by adding a `_redirects` file in your Astro project's `public/` folder. This file will be copied to your build output directory. For dynamic routes, [configure redirects in Astro directly](/en/guides/routing/#configured-redirects) instead. + +### Routes + +Routing for static assets is based on the file structure in the build directory (e.g. `./dist`). If no match is found, this will fall back to the Worker for on-demand rendering. Read more about [static asset routing with Cloudflare Workers](https://developers.cloudflare.com/workers/static-assets/routing/). + +## Sessions + +The Astro [Sessions API](/en/guides/sessions/) allows you to easily store user data between requests. This can be used for things like user data and preferences, shopping carts, and authentication credentials. Unlike cookie storage, there are no size limits on the data, and it can be restored on different devices. + +Astro automatically configures [Workers KV](https://developers.cloudflare.com/kv/) for session storage when using the Cloudflare adapter. Wrangler can [automatically provision](https://developers.cloudflare.com/workers/wrangler/configuration/#automatic-provisioning) the KV namespace when you deploy, so no manual setup is required. Alternatively, you can define the KV binding manually in your `wrangler.jsonc` file and set a custom binding name using the [`sessionKVBindingName`](#sessionkvbindingname) adapter option. + +```astro title="src/components/CartButton.astro" +--- +export const prerender = false; // Not needed in 'server' mode +const cart = await Astro.session?.get('cart'); +--- + +🛒 {cart?.length ?? 0} items +``` + +By default, the KV binding is named `SESSION`. To use a different name, set the [`sessionKVBindingName`](#sessionkvbindingname) option in the adapter config. + +:::note +Writes to Cloudflare KV are [eventually consistent](https://developers.cloudflare.com/kv/concepts/how-kv-works/#consistency) between regions. This means that changes are available immediately within the same region but may take up to 60 seconds to propagate globally. This won't affect most users as they are unlikely to switch regions between requests, but it may be a consideration for some use cases, such as VPN users. +::: + +## Cloudflare Module Imports + +The Cloudflare `workerd` runtime supports imports of some [non-standard module types](https://developers.cloudflare.com/workers/wrangler/bundling/#including-non-javascript-modules). Most additional file types are also available in Astro: + +- `.wasm` or `.wasm?module`: exports a [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Module) that can then be instantiated +- `.bin`: exports an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) of the raw binary contents of the file +- `.txt`: exports a string of the file contents + +All module types export a single default value. Modules can be imported both from server-side rendered pages, or from prerendered pages for static site generation. + +The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together. + +```js title="pages/add/[a]/[b].js" +// Import the WebAssembly module +import mod from '../util/add.wasm'; + +// Instantiate first in order to use it +const addModule: any = new WebAssembly.Instance(mod); + +export async function GET(context) { + const a = Number.parseInt(context.params.a); + const b = Number.parseInt(context.params.b); + return new Response(`${addModule.exports.add(a, b)}`); +} +``` + +While this example is trivial, Wasm can be used to accelerate computationally intensive operations which do not involve significant I/O such as embedding an image processing library, or embedding a small pre-indexed database for search over a read-only dataset. + +## Node.js compatibility + +Cloudflare Workers support most Node.js runtime APIs through the `nodejs_compat` compatibility flag. This includes commonly used modules like `node:buffer`, `node:crypto`, `node:path`, and many others. See the [full list of supported Node.js APIs](https://developers.cloudflare.com/workers/runtime-apis/nodejs) in Cloudflare's documentation. + +To enable Node.js compatibility, add the `nodejs_compat` flag to your Wrangler configuration: + +```jsonc title="wrangler.jsonc" +{ + "compatibility_flags": ["nodejs_compat"], +} +``` + +Then use the `node:*` import syntax in your server-side code: + +```js title="src/pages/api/endpoint.js" +export const prerender = false; // Not needed in 'server' mode +import { Buffer } from 'node:buffer'; +``` + +For Node.js APIs not yet supported in the Workers runtime, Wrangler can inject polyfills (requires `nodejs_compat` and a compatibility date of 2024-09-23 or later). + +See the [Cloudflare documentation on Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) for the complete list of supported APIs and configuration details. + +## Local preview + +After building your project with `astro build`, use `astro preview` to test your Cloudflare Workers application locally. The preview runs using Cloudflare's `workerd` runtime, closely mirroring production behavior. + +### Meaningful error messages + +By default, errors occurring while running your application in Wrangler are minified. For better debugging, add `vite.build.minify = false` to your `astro.config.mjs`: + +```js title="astro.config.mjs" ins={3-7} +export default defineConfig({ + adapter: cloudflare(), + vite: { + build: { + minify: false, + }, + }, +}); +``` + +## Upgrading to v13 and Astro 6 + +Astro 6 brings significant improvements to the Cloudflare development experience and requires `@astrojs/cloudflare` v13 or later. Now, `astro dev` uses Cloudflare's Vite plugin and `workerd` runtime to closely mirror production behavior. + +See [the Astro 6 upgrade guide](/en/guides/upgrade-to/v6/) for full instructions on upgrading Astro itself. + +### Development server now uses workerd + +The biggest change for Cloudflare users in Astro 6 is that `astro dev` and `astro preview` now use the Cloudflare Vite plugin to run your site using the real Workers runtime (`workerd`) instead of Node.js. This means your development environment is now a much closer replica of your production environment, with the same runtime, APIs, and behavior. + +This change helps you catch issues during development that would have previously only appeared in production, and features like Durable Objects, R2 bindings, and Workers AI now work exactly as they do when deployed to Cloudflare's platform. + +This change is transparent for most projects. If your project had special configuration for `astro dev` or was relying on Node.js-specific behavior in development, adjust your code or configuration accordingly. + +### New: `prerenderEnvironment` option + +In Astro 6, prerendered pages now run in Cloudflare's `workerd` runtime by default during development and build. Previously, these pages always ran in Node.js. + +If your prerendered pages depend on Node.js APIs (for example `node:fs`) or NPM packages that are not compatible with `workerd`, set `prerenderEnvironment: 'node'` in your Cloudflare adapter config to restore the previous behavior for prerendering. + +On-demand rendered pages are not affected by this option and continue to run in `workerd`. + +See [`prerenderEnvironment`](#prerenderenvironment) for configuration details. + +### Some dependencies might need to be pre-compiled + +The new workerd environment does not support CommonJS syntax, including Node.js specific syntax such as `require` and `module.exports`. This means that some of your project dependencies may throw errors in the development server or during the build. + +If you have control over the dependency, you can create a Vite plugin and pre-compile the dependency using the `optimizeDeps.include` option. + +For example, you can create a Vite plugin to pre-compile the dependency `postcss` in order to use the Expressive Code syntax highlighter: + +```js ins={8-14} +function noExternalPlugin() { + return { + name: "optimize-dependencies", + configEnvironment(environment) { + // We're only interested in server environments + if (environment !== 'client') { + return { + optimizeDeps: { + include: [ + "postcss" + // Or you can use this syntax if you don't depend directly on a dependency + // "expressive-code > postcss" + ] + } + } + } + } + } +} +``` + +### Changed: Wrangler entrypoint configuration + +Previously, the `main` field in your Wrangler configuration pointed to the built worker file (e.g. `dist/_worker.js/index.js`). With Astro 6, this has changed to point to a new unified entrypoint provided by the Cloudflare adapter: `@astrojs/cloudflare/entrypoints/server`. + +Update your `wrangler.jsonc` to use the new entrypoint: + +```jsonc title="wrangler.jsonc" del={2} ins={3} +{ + "main": "dist/_worker.js/index.js", + "main": "@astrojs/cloudflare/entrypoints/server", + "name": "my-astro-app", + // ... rest of config +} +``` + +This single entrypoint handles both `astro dev` and production deployments. + +### Removed: `Astro.locals.runtime` API + +The `Astro.locals.runtime` object has been removed in favor of direct access to Cloudflare Workers APIs. Access environment variables, the `cf` object, caches, and execution context directly through the provided interfaces. + +**Accessing environment variables:** + +Previously, environment variables were accessed through `Astro.locals.runtime.env`. Now import `env` directly instead: + +```js del={1} ins={2} +const { env } = Astro.locals.runtime; +import { env } from 'cloudflare:workers'; +``` + +**Accessing the `cf` object:** + +Previously, the `cf` object was accessed through `Astro.locals.runtime.cf`. Now access it directly from the request: + +```js del={1} ins={2} +const { cf } = Astro.locals.runtime; +const cf = Astro.request.cf; +``` + +**Accessing the caches API:** + +Previously, the caches API was accessed through `Astro.locals.runtime.caches`. Now use the global `caches` object directly: + +```js del={1} +const { caches } = Astro.locals.runtime; + +caches.default.put(request, response); +``` + +**Accessing the execution context:** + +The `Astro.locals.runtime.ctx` object is replaced with `Astro.locals.cfContext`, which contains the Cloudflare `ExecutionContext`: + +```js del={1} ins={2} +const ctx = Astro.locals.runtime.ctx; +const ctx = Astro.locals.cfContext; +``` + +### Changed: Wrangler configuration file is now optional + +The Wrangler configuration file is now optional for simple projects. If you don't have custom configuration, such as Cloudflare bindings (KV, D1, Durable Objects, etc.), Astro will automatically generate a default configuration for you. + +If your `wrangler.jsonc` only contains basic configuration like this: + +```jsonc +{ + "main": "@astrojs/cloudflare/entrypoints/server", + "compatibility_date": "2025-05-21", + "assets": { + "directory": "./dist", + "binding": "ASSETS", + }, +} +``` + +You can safely delete this file. Astro handles this configuration automatically. Alternatively, create a minimal `wrangler.jsonc` with just your project name and other custom settings: + +```jsonc title="wrangler.jsonc" +{ + "name": "my-astro-app", +} +``` + +### Changed: Custom entrypoint API + +If you were using a custom `workerEntryPoint` configuration in the adapter options, this has been removed. Instead, specify your custom entrypoint in your Wrangler configuration and create a standard Cloudflare Worker export object directly, rather than using the `createExports()` function. + + +1. Remove the `workerEntryPoint` option from your adapter config: + + ```js title="astro.config.mjs" del={6-9} + import { defineConfig } from 'astro/config'; + import cloudflare from '@astrojs/cloudflare'; + + export default defineConfig({ + adapter: cloudflare({ + workerEntryPoint: { + path: 'src/worker.ts', + namedExports: ['MyDurableObject'], + }, + }), + }); + ``` + +2. Specify the entrypoint in `wrangler.jsonc` instead: + + ```jsonc title="wrangler.jsonc" + { + "main": "./src/worker.ts" + } + ``` + +3. Update your custom worker entry file to use standard Worker syntax. Import the handler from `@astrojs/cloudflare/handler` and export a standard Cloudflare Worker object, alongside any custom exports like Durable Objects: + + ```ts title="src/worker.ts" + import { handle } from '@astrojs/cloudflare/handler'; + import { DurableObject } from 'cloudflare:workers'; + + export class MyDurableObject extends DurableObject { + // ... + } + + export default { + async fetch(request, env, ctx) { + await env.MY_QUEUE.send('log'); + return handle(request, env, ctx); + }, + async queue(batch, _env) { + let messages = JSON.stringify(batch.messages); + console.log(`consumed from our queue: ${messages}`); + }, + } satisfies ExportedHandler; + ``` + + +The manifest is now created internally by the adapter, so it does not need to be passed to your handler. + +### Removed: `cloudflareModules` option + +The `cloudflareModules` adapter option has been removed because it is no longer necessary. Cloudflare natively supports importing `.sql`, `.wasm`, and other module types. + +Remove the `cloudflareModules` option from your Cloudflare adapter configuration if you were using it: + +```ts title="astro.config.mjs" del={5} +import cloudflare from '@astrojs/cloudflare'; + +export default defineConfig({ + adapter: cloudflare({ + cloudflareModules: true + }) +}); +``` + + +### New: `astro preview` support + +Use `astro preview` to test your Cloudflare Workers application locally before deploying. The preview runs using Cloudflare's `workerd` runtime, closely mirroring production behavior. Run `astro build` followed by `astro preview` to start the preview server. + +### Removed: Cloudflare Pages support + +The Astro Cloudflare adapter no longer supports deployment on Cloudflare Pages. For the best experience and feature support, you should migrate to Cloudflare Workers. + +See Cloudflare's [migration guide from Pages to Workers](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/) for detailed migration instructions. + +### Changed: `imageService` default + +The default value of `imageService` has changed from `'compile'` to `'cloudflare-binding'` for an improved experience when working with images. + +The `cloudflare-binding` service uses the [Cloudflare Images binding](https://developers.cloudflare.com/images/transform-images/bindings/) to transform images at runtime, and the binding is automatically provisioned when you deploy. + +To revert to the previous behavior, where image transformation was only available on prerendered routes at build time, set `imageService: 'compile'` explicitly in your adapter config. + +### Changed: Deploy to Cloudflare Environment + +In Astro 5.x, you could build your Astro project once and deploy it to a specific Cloudflare environment with `wrangler deploy --env some-env`. + +Since Astro 6.0, the integration relies on the Cloudflare Vite plugin and this behavior has changed. The environment is now determined during the build phase. Therefore, you must build your project separately for each environment. + +To deploy to a specific Cloudflare environment, prefix your command with the `CLOUDFLARE_ENV` variable. For example, the command `CLOUDFLARE_ENV=some-env astro build && wrangler deploy` will build your Astro project and deploy it with Wrangler using the `some-env` environment. + +Learn how to update your [Cloudflare environments](https://developers.cloudflare.com/workers/vite-plugin/reference/cloudflare-environments/) in the [Migrate from wrangler dev guide](https://developers.cloudflare.com/workers/vite-plugin/reference/migrating-from-wrangler-dev/#cloudflare-environments). + +[astro-integration]: /en/guides/integrations/ From 2f7ca47bd75474c72501ade364d4fb7efc91b467 Mon Sep 17 00:00:00 2001 From: HakuRan Date: Mon, 1 Jun 2026 18:21:47 +0800 Subject: [PATCH 2/9] options --- .../guides/integrations-guide/cloudflare.mdx | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index cf6b7ec1148fb..870b1623d7c45 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -98,9 +98,9 @@ Astro 包含了一个 `astro add` 命令,用于自动设置官方集成。如 ``` -## Options +## 选项 -The Cloudflare adapter accepts the following options from [`@cloudflare/vite-plugin`](https://developers.cloudflare.com/workers/vite-plugin/): +Cloudflare 适配器使用来自 [`@cloudflare/vite-plugin`](https://developers.cloudflare.com/workers/vite-plugin/) 的以下选项 - `auxiliaryWorkers` - `configPath` @@ -109,24 +109,24 @@ The Cloudflare adapter accepts the following options from [`@cloudflare/vite-plu - `remoteBindings` - `experimental.headersAndRedirectsDevModeSupport` -It also accepts the following: +除此之外还可以使用以下选项: ### `imageService`

-**Type:** `'passthrough' | 'cloudflare' | 'cloudflare-binding' | 'compile' | 'custom' | { build: 'compile', runtime?: 'cloudflare-binding' | 'passthrough' }`
-**Default:** `'cloudflare-binding'` +**类型:** `'passthrough' | 'cloudflare' | 'cloudflare-binding' | 'compile' | 'custom' | { build: 'compile', runtime?: 'cloudflare-binding' | 'passthrough' }`
+**默认值:** `'cloudflare-binding'`

-Determines which image service is used by the adapter. The adapter will default to `cloudflare-binding` mode when an incompatible image service is configured. Otherwise, it will use the globally configured image service: +指定适配器使用哪个图像服务。当配置了不兼容的图像服务时,适配器将默认使用 `cloudflare-binding` 模式。否则,它将使用全局配置的图像服务: -- **`cloudflare`:** Uses the [Cloudflare Image Resizing](https://developers.cloudflare.com/images/image-resizing/) service. -- **`cloudflare-binding`:** Uses the [Cloudflare Images binding](https://developers.cloudflare.com/images/transform-images/bindings/) for image transformation. The binding is automatically provisioned when you deploy. -- **`passthrough`:** Uses the existing [`noop`](/en/guides/images/#configure-no-op-passthrough-service) service. -- **`compile`:** Uses a combination of internal dependencies to transform images locally at build time for prerendered routes. The noop `passthrough` option is configured for on-demand rendered pages. -- **`custom`:** Always uses the image service configured in [Image Options](/en/reference/configuration-reference/#image-options). **This option will not check to see whether the configured image service works in Cloudflare's `workerd` runtime.** +- **`cloudflare`:** 使用 [Cloudflare Image Resizing](https://developers.cloudflare.com/images/image-resizing/) 服务。 +- **`cloudflare-binding`:** 使用 [Cloudflare Images binding](https://developers.cloudflare.com/images/transform-images/bindings/) 来进行图像转换。该绑定会在你部署时自动配置。 +- **`passthrough`:** 使用现有的 [`noop`](/zh-cn/guides/images/#配置-no-op-透传服务) 服务。 +- **`compile`:** 使用内部依赖的组合,在构建时为预渲染路由在本地转换图像。对于按需渲染的页面,则配置了无操作的 `passthrough` 选项。 +- **`custom`:** 始终使用在 [Image Options](/zh-cn/reference/configuration-reference/#image-选项) 中配置的图像服务。**该选项不会检查所配置的图像服务是否能在 Cloudflare 的 `workerd` 运行时中正常工作。** -It is also possible to configure your image service as an object, setting both a build time and runtime service independently. Currently, `'compile'` is the only available build-time option. The supported runtime options are `'passthrough'` (default) and `'cloudflare-binding'`: +你也可以将图像服务配置为一个对象,分别独立设置构建时服务和运行时服务。目前,唯一可用的构建时选项是 `compile`。支持的运行时选项有 `passthrough`(默认)和 `cloudflare-binding`: ```js title="astro.config.mjs" ins={6} import { defineConfig } from 'astro/config'; @@ -142,12 +142,12 @@ export default defineConfig({ ### `sessionKVBindingName`

-**Type:** `string`
-**Default:** `SESSION` +**类型:** `string`
+**预设值:** `SESSION`

-Sets the name of the KV binding used for session storage. By default, the KV namespace is automatically provisioned when you deploy, and is named `SESSION`. You can change this name by setting the binding manually in your wrangler config. See [Sessions](#sessions) for more information. +设置用于会话存储的 KV 绑定的名称。默认情况下,KV 命名空间会在你部署时自动配置,并命名为 `SESSION`。你可以通过在 wrangler 配置中手动设置绑定来更改此名称。有关更多信息,请参阅[会话](#会话)部分。 ```js title="astro.config.mjs" "MY_SESSION_BINDING" export default defineConfig({ @@ -170,11 +170,11 @@ export default defineConfig({ ### `imagesBindingName`

-**Type:** `string`
-**Default:** `IMAGES` +**类型:** `string`
+**预设值:** `IMAGES`

-Sets the name of the Images binding used when [`imageService`](#imageservice) is set to `cloudflare-binding`. By default, the binding is automatically provisioned with the name `IMAGES` when you deploy. You can change it by setting the binding manually in your wrangler config: +当 [imageService](#imageservice) 设置为 `cloudflare-binding` 时所使用的 Images 绑定的名称。默认情况下,该绑定会在你部署时自动配置,并命名为 `IMAGES`。你可以通过在 wrangler 配置中手动设置绑定来更改它: ```js title="astro.config.mjs" "MY_IMAGES" export default defineConfig({ @@ -196,14 +196,14 @@ export default defineConfig({ ### `prerenderEnvironment`

-**Type:** `'workerd' | 'node'`
-**Default:** `'workerd'` +**类型:** `'workerd' | 'node'`
+**预设值:** `'workerd'`

-Controls which runtime is used for [prerendering](/en/guides/on-demand-rendering/) static pages at build time and during development. +控制构建时和开发期间用于[按需渲染](/zh-cn/guides/on-demand-rendering/)静态页面的运行时。 -By default, prerendered pages are built using Cloudflare's `workerd` runtime to match the production environment as closely as possible. Set this option to `'node'` when your prerendered pages depend on Node.js APIs or NPM packages that are not compatible with `workerd`: +默认情况下,按需渲染页面使用 Cloudflare 的 `workerd` 运行时构建,以尽可能贴近生产环境。当你的预渲染页面依赖与 workerd 不兼容的 Node.js API 或 NPM 包时,可将此选项设置为 `node`: ```js title="astro.config.mjs" "prerenderEnvironment" import { defineConfig } from 'astro/config'; @@ -216,9 +216,9 @@ export default defineConfig({ }); ``` -For example, if a prerendered page reads from the file system using `node:fs`, set `prerenderEnvironment` to `'node'`. On-demand rendered pages are unaffected by this option and always run in `workerd`. +例如,如果某个预渲染页面使用 `node:fs` 读取文件系统,请将 `prerenderEnvironment` 设置为 `node`。按需渲染页面不受此选项影响,并且始终在 workerd 中运行。 -## Cloudflare runtime +## Cloudflare 运行时 The Cloudflare runtime gives you access to environment variables, bindings to Cloudflare resources, and other Cloudflare-specific APIs. From 53076312ce385f5eff7732a2424092e9bd670b0f Mon Sep 17 00:00:00 2001 From: HakuRan Date: Mon, 1 Jun 2026 18:39:14 +0800 Subject: [PATCH 3/9] env --- .../guides/integrations-guide/cloudflare.mdx | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index 870b1623d7c45..718f5a85a3d05 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -220,15 +220,13 @@ export default defineConfig({ ## Cloudflare 运行时 -The Cloudflare runtime gives you access to environment variables, bindings to Cloudflare resources, and other Cloudflare-specific APIs. +Cloudflare 运行时让你能够使用环境变量,Cloudflare 资源绑定以及其他 Cloudflare 特有的 API。 -### Environment variables and bindings +### 环境变量与绑定 -Environment variables and bindings are defined in your `wrangler.jsonc` configuration file. +环境变量和绑定要在 `wrangler.jsonc` 配置文件中进行定义。 - - -Define [environment variables](https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-wrangler) that do not store sensitive information in `wrangler.jsonc`: +不要在 `wrangler.jsonc` 的[环境变量](https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-wrangler)中储存敏感信息。 ```jsonc title="wrangler.jsonc" { @@ -237,22 +235,22 @@ Define [environment variables](https://developers.cloudflare.com/workers/configu }, } ``` + +[Secrets](https://developers.cloudflare.com/workers/configuration/secrets/) 是特殊类型的环境变量。它能让你为 Worker 附加加密的文本值。它们需要以不同的方式定义,以确保在设置完成后,不会在 Wrangler 或 Cloudflare 仪表板中明文可见。 -[Secrets](https://developers.cloudflare.com/workers/configuration/secrets/) are a special type of environment variable that allow you to attach encrypted text values to your Worker. They need to be defined differently to ensure they are not visible within Wrangler or Cloudflare dashboard after you set them. - -To define `secrets`, add them through the [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) rather than in your Wrangler config file: +要定义 `secrets`,请通过 [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) 而不是在 Wrangler 配置文件中添加: ```bash npx wrangler secret put ``` -To set secrets for local development, add a `.dev.vars` file to the root of the Astro project: +如果要为本地开发设置机密,请在 Astro 项目的根目录中添加 `.dev.vars` 文件: ```ini title=".dev.vars" DB_PASSWORD=myPassword ``` -Cloudflare environment variables and secrets can be imported from `"cloudflare:workers"`: +Cloudflare 的环境变量和 secrets 可以使用 `"cloudflare:workers"` 进行导入: ```astro title="src/pages/index.astro" --- @@ -263,13 +261,13 @@ const myKVNamespace = env.MY_KV; --- ``` -They are also compatible with the [`astro:env` API](/en/guides/environment-variables/#type-safe-environment-variables): +也可以使用 [`astro:env` API](/zh-cn/guides/environment-variables/#类型安全的环境变量): ```js import { MY_VARIABLE } from 'astro:env/server'; ``` -See the [list of all supported bindings](https://developers.cloudflare.com/workers/wrangler/api/#supported-bindings) in the Cloudflare documentation. +请在 Cloudflare 文档中查看[所有支持的绑定](https://developers.cloudflare.com/workers/wrangler/api/#supported-bindings)。 ### The `cf` object From a58d4ac7b82d9686b6b18c4d69ed0974ad1babb4 Mon Sep 17 00:00:00 2001 From: HakuRan Date: Wed, 3 Jun 2026 12:58:04 +0800 Subject: [PATCH 4/9] cf platform --- .../guides/integrations-guide/cloudflare.mdx | 41 +++++++++---------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index 718f5a85a3d05..b9da1721cb3a9 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -236,7 +236,7 @@ Cloudflare 运行时让你能够使用环境变量,Cloudflare 资源绑定以 } ``` -[Secrets](https://developers.cloudflare.com/workers/configuration/secrets/) 是特殊类型的环境变量。它能让你为 Worker 附加加密的文本值。它们需要以不同的方式定义,以确保在设置完成后,不会在 Wrangler 或 Cloudflare 仪表板中明文可见。 +[Secrets](https://developers.cloudflare.com/workers/configuration/secrets/) 是特殊类型的环境变量。它能让你为 Worker 添加加密的文本值。它们需要以不同的方式定义,以确保在设置完成后,不会在 Wrangler 或 Cloudflare 仪表板中明文可见。 要定义 `secrets`,请通过 [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) 而不是在 Wrangler 配置文件中添加: @@ -244,7 +244,7 @@ Cloudflare 运行时让你能够使用环境变量,Cloudflare 资源绑定以 npx wrangler secret put ``` -如果要为本地开发设置机密,请在 Astro 项目的根目录中添加 `.dev.vars` 文件: +如果要为本地开发设置 `secret`,请在 Astro 项目的根目录中添加 `.dev.vars` 文件: ```ini title=".dev.vars" DB_PASSWORD=myPassword @@ -269,9 +269,9 @@ import { MY_VARIABLE } from 'astro:env/server'; 请在 Cloudflare 文档中查看[所有支持的绑定](https://developers.cloudflare.com/workers/wrangler/api/#supported-bindings)。 -### The `cf` object +### `cf` 对象 -The Cloudflare [`cf` object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties) contains request metadata such as geolocation information. Access it directly from the request: +Cloudflare 的 [`cf` 对象](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties)包含请求的地理信息等元数据。 可以直接在请求中访问它: ```astro title="src/pages/index.astro" --- @@ -280,9 +280,9 @@ const country = cf?.country; --- ``` -### Execution context +### 执行上下文 -Access the Cloudflare [`ExecutionContext`](https://developers.cloudflare.com/workers/runtime-apis/context/) through `Astro.locals.cfContext`. This is useful for operations like [`waitUntil()`](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil), or accessing [Durable Object exports](https://developers.cloudflare.com/workers/runtime-apis/context/#exports) within your page. +通过 `Astro.locals.cfContext` 可以访问 Cloudflare 的[`执行上下文`](https://developers.cloudflare.com/workers/runtime-apis/context/)。 这对于 [`waitUntil()`](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil) 等操作,或者在页面中访问 [Durable Object exports](https://developers.cloudflare.com/workers/runtime-apis/context/#exports) 时非常有用。 ```astro title="src/pages/index.astro" --- @@ -292,15 +292,14 @@ cfContext.waitUntil(someAsyncOperation()); --- ``` -### Typing +### 类型定义 -`wrangler` provides a [`types`](https://developers.cloudflare.com/workers/wrangler/commands/#types) command to generate TypeScript types for your bindings. This allows you to type your environment without the need for manual type definitions. +`wrangler` 提供了一个 [`types`](https://developers.cloudflare.com/workers/wrangler/commands/#types) 命令来为你的绑定生成 TypeScript 类型。这让你无需手动定义类型即可为环境添加类型。 -Run `wrangler types` every time you change your configuration files (e.g. `wrangler.jsonc`, `.dev.vars`). +每次更改配置文件(例如 `wrangler.jsonc`, `.dev.vars` )时,请运行 `wrangler types`。 :::note -The following example shows a script configuration to run `wrangler types` automatically before other commands: - +以下示例展示了一个脚本配置,用于在其他命令之前自动运行 `wrangler types`: ```json title="package.json" { "scripts": { @@ -315,23 +314,23 @@ The following example shows a script configuration to run `wrangler types` autom ::: -## Cloudflare Platform - -### Headers +## Cloudflare 平台 -Add [custom headers](https://developers.cloudflare.com/workers/static-assets/headers/) for static assets by creating a `_headers` file in your Astro project's `public/` folder. This file will be copied to the build output directory. Headers in `_headers` are not applied to responses generated by your Worker code. +### 标头 -### Assets +通过在你的 Astro 项目的 `public/` 文件夹中创建 `_headers` 文件,可以为你的静态资源创建[自定义标头](https://developers.cloudflare.com/workers/static-assets/headers/)。该文件将会被复制到你的构建输出目录里。`_headers` 文件里设置的标头不会自动添加到你的 Worker 代码生成的响应中。 -Assets built by Astro are all named with a hash and, therefore, can be given long cache headers. By default, Astro on Cloudflare will add such a header for these files. +### 资源 -### Redirects +Astro 构建出的资源都都使用哈希值命名,因此可以为它们设置较长的缓存标头。默认情况下,部署在 Cloudflare 上的 Astro 会为这些文件添加此类标头。 -Declare [custom redirects for static assets](https://developers.cloudflare.com/workers/static-assets/redirects/) by adding a `_redirects` file in your Astro project's `public/` folder. This file will be copied to your build output directory. For dynamic routes, [configure redirects in Astro directly](/en/guides/routing/#configured-redirects) instead. +### 重定向 + +通过在 Astro 项目的 `public/` 文件夹中添加 `_redirects` 文件,可以为静态资源声明[自定义重定向](https://developers.cloudflare.com/workers/static-assets/redirects/)。该文件将会被复制到你的构建输出目录里。对于动态路由,请查看 Astro 的[配置重定向](/zh-cn/guides/routing/#配置重定向). -### Routes +### 路由 -Routing for static assets is based on the file structure in the build directory (e.g. `./dist`). If no match is found, this will fall back to the Worker for on-demand rendering. Read more about [static asset routing with Cloudflare Workers](https://developers.cloudflare.com/workers/static-assets/routing/). +静态资源的路由基于构建目录(如 ./dist)中的文件结构。如果未找到匹配项,则会回退到 Worker 进行按需渲染。更多信息,请参阅 [Cloudflare Workers 进行静态资源路由](https://developers.cloudflare.com/workers/static-assets/routing/)。 ## Sessions From 47afd7a5c0807e39a30c932f9ba6cb56cffdc8a9 Mon Sep 17 00:00:00 2001 From: HakuRan Date: Wed, 3 Jun 2026 13:11:26 +0800 Subject: [PATCH 5/9] cf sessions --- .../zh-cn/guides/integrations-guide/cloudflare.mdx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index b9da1721cb3a9..5a029042dd398 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -92,7 +92,7 @@ Astro 包含了一个 `astro add` 命令,用于自动设置官方集成。如 ```jsonc title="wrangler.jsonc" { "name": "my-astro-app", - // Add your bindings here, e.g.: + // 在此添加你的绑定 // "kv_namespaces": [{ "binding": "MY_KV", "id": "" }] } ``` @@ -332,25 +332,25 @@ Astro 构建出的资源都都使用哈希值命名,因此可以为它们设 静态资源的路由基于构建目录(如 ./dist)中的文件结构。如果未找到匹配项,则会回退到 Worker 进行按需渲染。更多信息,请参阅 [Cloudflare Workers 进行静态资源路由](https://developers.cloudflare.com/workers/static-assets/routing/)。 -## Sessions +## 会话 -The Astro [Sessions API](/en/guides/sessions/) allows you to easily store user data between requests. This can be used for things like user data and preferences, shopping carts, and authentication credentials. Unlike cookie storage, there are no size limits on the data, and it can be restored on different devices. +Astro 的[会话 API](/zh-cn/guides/sessions/) 让你可以轻松地在多个请求之间存储用户数据。这可用于用户数据与偏好设置、购物车以及身份验证凭据等场景。与 Cookie 存储不同,会话数据没有大小限制,并且可以在不同设备上恢复。 -Astro automatically configures [Workers KV](https://developers.cloudflare.com/kv/) for session storage when using the Cloudflare adapter. Wrangler can [automatically provision](https://developers.cloudflare.com/workers/wrangler/configuration/#automatic-provisioning) the KV namespace when you deploy, so no manual setup is required. Alternatively, you can define the KV binding manually in your `wrangler.jsonc` file and set a custom binding name using the [`sessionKVBindingName`](#sessionkvbindingname) adapter option. +使用 Cloudflare 适配器时,Astro 会自动为会话存储配置 [Workers KV](https://developers.cloudflare.com/kv/)。Wrangler 可以在你部署时[自动配置](https://developers.cloudflare.com/workers/wrangler/configuration/#automatic-provisioning) KV 命名空间,因此无需手动设置。或者,你也可以在 `wrangler.jsonc` 文件中手动定义 KV 绑定,并使用 [`sessionKVBindingName`](#sessionkvbindingname) 适配器选项来设置自定义绑定名称。 ```astro title="src/components/CartButton.astro" --- -export const prerender = false; // Not needed in 'server' mode +export const prerender = false; // 在 'server' 模式中不需要 const cart = await Astro.session?.get('cart'); --- 🛒 {cart?.length ?? 0} items ``` -By default, the KV binding is named `SESSION`. To use a different name, set the [`sessionKVBindingName`](#sessionkvbindingname) option in the adapter config. +认情况下,KV 绑定命名为 `SESSION`。如果要使用不同的名称,请在适配器配置中设置 [`sessionKVBindingName`](#sessionkvbindingname) 选项。 :::note -Writes to Cloudflare KV are [eventually consistent](https://developers.cloudflare.com/kv/concepts/how-kv-works/#consistency) between regions. This means that changes are available immediately within the same region but may take up to 60 seconds to propagate globally. This won't affect most users as they are unlikely to switch regions between requests, but it may be a consideration for some use cases, such as VPN users. +向 Cloudflare KV 写入数据在区域间遵循[最终一致性](https://developers.cloudflare.com/kv/concepts/how-kv-works/#consistency)。这意味着变更在同一区域立即生效,但在全球范围同步可能需要最多 60 秒。对于大多数用户来说,这一点不会产生影响,因为他们在请求之间不太可能切换区域,但某些使用场景仍需考量,比如使用 VPN 的用户。 ::: ## Cloudflare Module Imports From bdae61d3c12e2ab4ccd82e513cb1182ffc6c4f6c Mon Sep 17 00:00:00 2001 From: HakuRan Date: Wed, 3 Jun 2026 13:49:01 +0800 Subject: [PATCH 6/9] cf --- .../guides/integrations-guide/cloudflare.mdx | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index 5a029042dd398..69734523d6735 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -353,23 +353,25 @@ const cart = await Astro.session?.get('cart'); 向 Cloudflare KV 写入数据在区域间遵循[最终一致性](https://developers.cloudflare.com/kv/concepts/how-kv-works/#consistency)。这意味着变更在同一区域立即生效,但在全球范围同步可能需要最多 60 秒。对于大多数用户来说,这一点不会产生影响,因为他们在请求之间不太可能切换区域,但某些使用场景仍需考量,比如使用 VPN 的用户。 ::: -## Cloudflare Module Imports +## Cloudflare 模块导入 -The Cloudflare `workerd` runtime supports imports of some [non-standard module types](https://developers.cloudflare.com/workers/wrangler/bundling/#including-non-javascript-modules). Most additional file types are also available in Astro: +Cloudflare 的 `workerd` 运行时支持导入某些[非标准模块类型](https://developers.cloudflare.com/workers/wrangler/bundling/#including-non-javascript-modules)。大多数其他文件类型在 Astro 中同样可用: -- `.wasm` or `.wasm?module`: exports a [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Module) that can then be instantiated -- `.bin`: exports an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) of the raw binary contents of the file -- `.txt`: exports a string of the file contents +- `.wasm` 或 `.wasm?module`:导出 [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Module),之后可对其进行实例化 -All module types export a single default value. Modules can be imported both from server-side rendered pages, or from prerendered pages for static site generation. +- `.bin`:导出文件的原始二进制内容所对应的 [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) -The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together. +- `.txt`:导出文件内容所对应的字符串 + +所有模块类型均导出一个默认值。这些模块既可以从服务端渲染页面中导入,也可以从用于静态站点生成的预渲染页面中导入。 + +下面是一个导入 Wasm 模块的示例,该模块通过将请求中的数字参数相加来响应请求。 ```js title="pages/add/[a]/[b].js" -// Import the WebAssembly module +// 导入 WebAssembly 模块 import mod from '../util/add.wasm'; -// Instantiate first in order to use it +// 先进行实例化,然后使用它。 const addModule: any = new WebAssembly.Instance(mod); export async function GET(context) { @@ -381,11 +383,11 @@ export async function GET(context) { While this example is trivial, Wasm can be used to accelerate computationally intensive operations which do not involve significant I/O such as embedding an image processing library, or embedding a small pre-indexed database for search over a read-only dataset. -## Node.js compatibility +## Node.js 兼容性 -Cloudflare Workers support most Node.js runtime APIs through the `nodejs_compat` compatibility flag. This includes commonly used modules like `node:buffer`, `node:crypto`, `node:path`, and many others. See the [full list of supported Node.js APIs](https://developers.cloudflare.com/workers/runtime-apis/nodejs) in Cloudflare's documentation. +Cloudflare Workers 通过 `nodejs_compat` 兼容性标志支持大多数 Node.js 运行时 API。这包括常用的模块,如 `node:buffer`,`node:crypto`,`node:path` 等。有关支持的 [Node.js API的完整列表](https://developers.cloudflare.com/workers/runtime-apis/nodejs),请参阅 Cloudflare 文档。 -To enable Node.js compatibility, add the `nodejs_compat` flag to your Wrangler configuration: +要启用 Node.js 兼容性,请在你的 Wrangler 配置中添加 `nodejs_compat` 标志: ```jsonc title="wrangler.jsonc" { @@ -393,24 +395,24 @@ To enable Node.js compatibility, add the `nodejs_compat` flag to your Wrangler c } ``` -Then use the `node:*` import syntax in your server-side code: +然后在你的服务端代码中使用 `node:*` 导入: ```js title="src/pages/api/endpoint.js" -export const prerender = false; // Not needed in 'server' mode +export const prerender = false; // 在 'server' 模式中不需要 import { Buffer } from 'node:buffer'; ``` -For Node.js APIs not yet supported in the Workers runtime, Wrangler can inject polyfills (requires `nodejs_compat` and a compatibility date of 2024-09-23 or later). +对于 Workers 运行时尚未支持的 Node.js API,Wrangler 可以注入 polyfills(需要 `nodejs_compat` 以及兼容性日期为 2024 年 9 月 23 日或之后)。 -See the [Cloudflare documentation on Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) for the complete list of supported APIs and configuration details. +有关支持的 API 完整列表和配置详情,请参阅 [Cloudflare 关于 Node.js 兼容性的文档](https://developers.cloudflare.com/workers/runtime-apis/nodejs/)。 -## Local preview +## 本地预览 -After building your project with `astro build`, use `astro preview` to test your Cloudflare Workers application locally. The preview runs using Cloudflare's `workerd` runtime, closely mirroring production behavior. +使用 `astro build` 构建项目后,可以使用 `astro preview` 在本地测试你的 Cloudflare Workers 应用。该预览会使用 Cloudflare 的 `workerd` 运行时,其运行行为与生产环境高度一致, -### Meaningful error messages +### 有意义的错误信息 -By default, errors occurring while running your application in Wrangler are minified. For better debugging, add `vite.build.minify = false` to your `astro.config.mjs`: +默认情况下,在 Wrangler 中运行应用时发生的错误会被压缩。为了更好地调试,请在 `astro.config.mjs` 中添加 `vite.build.minify = false`: ```js title="astro.config.mjs" ins={3-7} export default defineConfig({ @@ -423,7 +425,7 @@ export default defineConfig({ }); ``` -## Upgrading to v13 and Astro 6 +## 升级到 v13 和 Astro 6 Astro 6 brings significant improvements to the Cloudflare development experience and requires `@astrojs/cloudflare` v13 or later. Now, `astro dev` uses Cloudflare's Vite plugin and `workerd` runtime to closely mirror production behavior. From b82771dc46351228894978f3056296fec8c5f76c Mon Sep 17 00:00:00 2001 From: HakuRan Date: Wed, 3 Jun 2026 14:36:45 +0800 Subject: [PATCH 7/9] i18n(zh-cn): add cloudflare.mdx --- .../guides/integrations-guide/cloudflare.mdx | 129 +++++++++--------- 1 file changed, 67 insertions(+), 62 deletions(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index 69734523d6735..0211f65dde58a 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -26,7 +26,7 @@ Astro 6 需要将次适配器更新到 v13。 关于重大变更和迁移指南 ## 为什么选择 Cloudflare? -Cloudflare 的 [开发者平台](https://developers.cloudflare.com/) 能够让你开发全栈应用,并访问存储、AI 等资源,所有内容都部署到全球边缘网络上。该适配器会构建你的 Astro 项目,并通过 Cloudflare 进行部署。 +Cloudflare 的 [开发者平台](https://developers.cloudflare.com/) 能够让你开发全栈应用,并访问存储,AI 等资源,所有内容都部署到全球边缘网络上。该适配器会构建你的 Astro 项目,并通过 Cloudflare 进行部署。 ## 安装 @@ -334,7 +334,7 @@ Astro 构建出的资源都都使用哈希值命名,因此可以为它们设 ## 会话 -Astro 的[会话 API](/zh-cn/guides/sessions/) 让你可以轻松地在多个请求之间存储用户数据。这可用于用户数据与偏好设置、购物车以及身份验证凭据等场景。与 Cookie 存储不同,会话数据没有大小限制,并且可以在不同设备上恢复。 +Astro 的[会话 API](/zh-cn/guides/sessions/) 让你可以轻松地在多个请求之间存储用户数据。这可用于用户数据与偏好设置,购物车以及身份验证凭据等场景。与 Cookie 存储不同,会话数据没有大小限制,并且可以在不同设备上恢复。 使用 Cloudflare 适配器时,Astro 会自动为会话存储配置 [Workers KV](https://developers.cloudflare.com/kv/)。Wrangler 可以在你部署时[自动配置](https://developers.cloudflare.com/workers/wrangler/configuration/#automatic-provisioning) KV 命名空间,因此无需手动设置。或者,你也可以在 `wrangler.jsonc` 文件中手动定义 KV 绑定,并使用 [`sessionKVBindingName`](#sessionkvbindingname) 适配器选项来设置自定义绑定名称。 @@ -427,48 +427,48 @@ export default defineConfig({ ## 升级到 v13 和 Astro 6 -Astro 6 brings significant improvements to the Cloudflare development experience and requires `@astrojs/cloudflare` v13 or later. Now, `astro dev` uses Cloudflare's Vite plugin and `workerd` runtime to closely mirror production behavior. +Astro 6 为 Cloudflare 开发体验带来了显著改进,并且需要 `@astrojs/cloudflare` v13 或更高版本。现在,`astro dev` 使用 Cloudflare 的 Vite 插件和 `workerd` 运行时,其运行行为与生产环境高度一致。 -See [the Astro 6 upgrade guide](/en/guides/upgrade-to/v6/) for full instructions on upgrading Astro itself. +有关升级 Astro 本身的完整说明,请参阅 [Astro 6 升级指南](/zh-cn/guides/upgrade-to/v6/)。 -### Development server now uses workerd +### 开发服务器现在使用 workerd -The biggest change for Cloudflare users in Astro 6 is that `astro dev` and `astro preview` now use the Cloudflare Vite plugin to run your site using the real Workers runtime (`workerd`) instead of Node.js. This means your development environment is now a much closer replica of your production environment, with the same runtime, APIs, and behavior. +Astro 6 为 Cloudflare 用户带来的最大变化是 `astro dev` 和 `astro preview` 现在使用 Cloudflare Vite 插件,通过真实的 Workers 运行时(`workerd`)而非 Node.js 来运行你的站点。这意味着你的开发环境现在与生产环境高度接近,拥有相同的运行时,API 和行为。 -This change helps you catch issues during development that would have previously only appeared in production, and features like Durable Objects, R2 bindings, and Workers AI now work exactly as they do when deployed to Cloudflare's platform. +这一变化有助于你在开发阶段就能发现之前只在生产环境中才会出现的问题,而且像 Durable Objects,R2 绑定和 Workers AI 等功能现在的工作方式与部署到 Cloudflare 平台时完全一致。 -This change is transparent for most projects. If your project had special configuration for `astro dev` or was relying on Node.js-specific behavior in development, adjust your code or configuration accordingly. +对于大多数项目来说,这一变化是透明的。如果你的项目为 `astro dev` 做了特殊配置,或者依赖开发环境中的 Node.js 特定行为,请相应调整代码或配置。 -### New: `prerenderEnvironment` option +### 添加:`prerenderEnvironment` 选项 -In Astro 6, prerendered pages now run in Cloudflare's `workerd` runtime by default during development and build. Previously, these pages always ran in Node.js. +在 Astro 6 中,预渲染页面在开发和构建期间默认会在 Cloudflare 的 `workerd` 运行时中运行。以前,这些页面始终在 Node.js 中运行。 -If your prerendered pages depend on Node.js APIs (for example `node:fs`) or NPM packages that are not compatible with `workerd`, set `prerenderEnvironment: 'node'` in your Cloudflare adapter config to restore the previous behavior for prerendering. +如果你的预渲染页面依赖与 `workerd` 不兼容的 Node.js API(例如 node:fs)或 NPM 包,请在 Cloudflare 适配器配置中设置 `prerenderEnvironment: 'node'`,以恢复预渲染的先前行为。 -On-demand rendered pages are not affected by this option and continue to run in `workerd`. +按需渲染页面不受此选项影响,并且会继续在 `workerd` 中运行。 -See [`prerenderEnvironment`](#prerenderenvironment) for configuration details. +有关配置详情,请参阅 [`prerenderEnvironment`](#prerenderenvironment)。 -### Some dependencies might need to be pre-compiled +### 某些依赖可能需要预编译 -The new workerd environment does not support CommonJS syntax, including Node.js specific syntax such as `require` and `module.exports`. This means that some of your project dependencies may throw errors in the development server or during the build. +新的 workerd 环境不支持 CommonJS 语法,包括 Node.js 特有的语法如 `require` 和 `module.exports`。这意味着你项目中的某些依赖可能会在开发服务器中或构建期间抛出错误。 -If you have control over the dependency, you can create a Vite plugin and pre-compile the dependency using the `optimizeDeps.include` option. +如果你可以控制该依赖,可以创建一个 Vite 插件并使用 `optimizeDeps.include` 选项对该依赖进行预编译。 -For example, you can create a Vite plugin to pre-compile the dependency `postcss` in order to use the Expressive Code syntax highlighter: +例如,你可以创建一个 Vite 插件来预编译 `postcss` 依赖,以便使用 Expressive Code 语法高亮器: ```js ins={8-14} function noExternalPlugin() { return { name: "optimize-dependencies", configEnvironment(environment) { - // We're only interested in server environments + // 我们只关心服务器环境 if (environment !== 'client') { return { optimizeDeps: { include: [ "postcss" - // Or you can use this syntax if you don't depend directly on a dependency + // 或者,如果你不直接依赖某个依赖项,可以使用这种语法 // "expressive-code > postcss" ] } @@ -479,48 +479,48 @@ function noExternalPlugin() { } ``` -### Changed: Wrangler entrypoint configuration +### 更改:Wrangler 入口点配置 -Previously, the `main` field in your Wrangler configuration pointed to the built worker file (e.g. `dist/_worker.js/index.js`). With Astro 6, this has changed to point to a new unified entrypoint provided by the Cloudflare adapter: `@astrojs/cloudflare/entrypoints/server`. +以前,Wrangler 配置中的 `main` 字段指向构建后的 worker 文件(例如 `dist/_worker.js/index.js`)。在 Astro 6 中,该字段已改为指向 Cloudflare 适配器提供的新的统一入口点:`@astrojs/cloudflare/entrypoints/server`。 -Update your `wrangler.jsonc` to use the new entrypoint: +请更新你的 wrangler.jsonc 以使用新的入口点: ```jsonc title="wrangler.jsonc" del={2} ins={3} { "main": "dist/_worker.js/index.js", "main": "@astrojs/cloudflare/entrypoints/server", "name": "my-astro-app", - // ... rest of config + // ... 其他配置 } ``` -This single entrypoint handles both `astro dev` and production deployments. +这个单一的入口点同时处理 `astro dev` 和生产部署。 -### Removed: `Astro.locals.runtime` API +### 移除:`Astro.locals.runtime` API -The `Astro.locals.runtime` object has been removed in favor of direct access to Cloudflare Workers APIs. Access environment variables, the `cf` object, caches, and execution context directly through the provided interfaces. +`Astro.locals.runtime` 对象已被移除,取而代之的是直接访问 Cloudflare Workers API。通过提供的接口直接访问环境变量,`cf` 对象,缓存和执行上下文。 -**Accessing environment variables:** +**访问环境变量:** -Previously, environment variables were accessed through `Astro.locals.runtime.env`. Now import `env` directly instead: +以前,环境变量是通过 `Astro.locals.runtime.env` 访问的。现在,请改为直接导入 `env`: ```js del={1} ins={2} const { env } = Astro.locals.runtime; import { env } from 'cloudflare:workers'; ``` -**Accessing the `cf` object:** +**访问 `cf` 对象:** -Previously, the `cf` object was accessed through `Astro.locals.runtime.cf`. Now access it directly from the request: +以前,`cf` 对象是通过 `Astro.locals.runtime.cf` 访问的。现在,请直接从请求中访问它: ```js del={1} ins={2} const { cf } = Astro.locals.runtime; const cf = Astro.request.cf; ``` -**Accessing the caches API:** +**访问缓存 API:** -Previously, the caches API was accessed through `Astro.locals.runtime.caches`. Now use the global `caches` object directly: +以前,缓存 API 是通过 `Astro.locals.runtime.caches` 访问的。现在,请直接使用全局 `caches` 对象: ```js del={1} const { caches } = Astro.locals.runtime; @@ -528,20 +528,20 @@ const { caches } = Astro.locals.runtime; caches.default.put(request, response); ``` -**Accessing the execution context:** +**访问执行上下文:** -The `Astro.locals.runtime.ctx` object is replaced with `Astro.locals.cfContext`, which contains the Cloudflare `ExecutionContext`: +`Astro.locals.runtime.ctx` 对象已被 `Astro.locals.cfContext` 替代,后者包含 Cloudflare 的 `ExecutionContext`: ```js del={1} ins={2} const ctx = Astro.locals.runtime.ctx; const ctx = Astro.locals.cfContext; ``` -### Changed: Wrangler configuration file is now optional +### 更改:Wrangler 配置文件现在变为可选 -The Wrangler configuration file is now optional for simple projects. If you don't have custom configuration, such as Cloudflare bindings (KV, D1, Durable Objects, etc.), Astro will automatically generate a default configuration for you. +对于简单项目,Wrangler 配置文件现在变为可选。如果你没有自定义配置,比如 Cloudflare 绑定 (KV,D1,Durable Objects 等),Astro 将自动为你生成默认配置。 -If your `wrangler.jsonc` only contains basic configuration like this: +如果你的 `wrangler.jsonc` 只包含如下基本配置: ```jsonc { @@ -554,7 +554,7 @@ If your `wrangler.jsonc` only contains basic configuration like this: } ``` -You can safely delete this file. Astro handles this configuration automatically. Alternatively, create a minimal `wrangler.jsonc` with just your project name and other custom settings: +你可以安全地删除该文件。Astro 会自动处理此配置。或者,创建一个简单的 `wrangler.jsonc`,只包含你的项目名称和其他自定义设置即可。 ```jsonc title="wrangler.jsonc" { @@ -562,12 +562,12 @@ You can safely delete this file. Astro handles this configuration automatically. } ``` -### Changed: Custom entrypoint API +### 自定义入口点 API -If you were using a custom `workerEntryPoint` configuration in the adapter options, this has been removed. Instead, specify your custom entrypoint in your Wrangler configuration and create a standard Cloudflare Worker export object directly, rather than using the `createExports()` function. +如果你之前在适配器选项中使用了自定义的 `workerEntryPoint` 配置,该配置已被移除。取而代之的是,你需要在 Wrangler 配置中指定自定义入口点,并直接创建一个标准的 Cloudflare Worker 导出对象,而不是使用 `createExports()` 函数。 - -1. Remove the `workerEntryPoint` option from your adapter config: + +1. 从适配器配置中移除 `workerEntryPoint` 选项: ```js title="astro.config.mjs" del={6-9} import { defineConfig } from 'astro/config'; @@ -583,7 +583,7 @@ If you were using a custom `workerEntryPoint` configuration in the adapter optio }); ``` -2. Specify the entrypoint in `wrangler.jsonc` instead: +2. 改为在 `wrangler.jsonc` 中指定入口点: ```jsonc title="wrangler.jsonc" { @@ -591,7 +591,7 @@ If you were using a custom `workerEntryPoint` configuration in the adapter optio } ``` -3. Update your custom worker entry file to use standard Worker syntax. Import the handler from `@astrojs/cloudflare/handler` and export a standard Cloudflare Worker object, alongside any custom exports like Durable Objects: +3. 将你的自定义 Worker 入口文件更新为使用标准 Worker 语法。从 `@astrojs/cloudflare/handler` 导入处理函数,并导出一个标准的 Cloudflare Worker 对象,以及任何自定义导出(例如 Durable Objects): ```ts title="src/worker.ts" import { handle } from '@astrojs/cloudflare/handler'; @@ -614,13 +614,13 @@ If you were using a custom `workerEntryPoint` configuration in the adapter optio ``` -The manifest is now created internally by the adapter, so it does not need to be passed to your handler. +现在清单由适配器内部创建,因此不再需要将其传递给处理函数。 -### Removed: `cloudflareModules` option +### 移除:`cloudflareModules` 选项 -The `cloudflareModules` adapter option has been removed because it is no longer necessary. Cloudflare natively supports importing `.sql`, `.wasm`, and other module types. +`cloudflareModules` 适配器选项已被移除。Cloudflare 原生支持导入 `.sql`,`.wasm` 以及其他模块类型。 -Remove the `cloudflareModules` option from your Cloudflare adapter configuration if you were using it: +如果你之前使用了该选项,请从 Cloudflare 适配器配置中将其移除。 ```ts title="astro.config.mjs" del={5} import cloudflare from '@astrojs/cloudflare'; @@ -633,32 +633,37 @@ export default defineConfig({ ``` -### New: `astro preview` support +### 添加:`astro preview` 支持 + +在部署之前,请使用 `astro preview` 在本地测试你的 Cloudflare Workers 应用。该预览使用 Cloudflare 的 `workerd` 运行时,其运行行为与生产环境高度一致。先运行 `astro build`,再运行 `astro preview` 以启动预览服务器。 Use `astro preview` to test your Cloudflare Workers application locally before deploying. The preview runs using Cloudflare's `workerd` runtime, closely mirroring production behavior. Run `astro build` followed by `astro preview` to start the preview server. -### Removed: Cloudflare Pages support +### 移除:Cloudflare Pages 支持 + +Astro Cloudflare 适配器不再支持部署到 Cloudflare Pages。为了获得最佳体验和功能支持,你应该迁移到 Cloudflare Workers。 + +有关详细的迁移说明,请参阅 Cloudflare 的[从 Pages 迁移到 Workers 的指南](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/)。 + -The Astro Cloudflare adapter no longer supports deployment on Cloudflare Pages. For the best experience and feature support, you should migrate to Cloudflare Workers. +### 更改:`imageService` 默认值 -See Cloudflare's [migration guide from Pages to Workers](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/) for detailed migration instructions. +为了改善使用图像时的体验,`imageService` 的默认值已从 `compile` 改为 `cloudflare-binding`。 -### Changed: `imageService` default +`cloudflare-binding` 服务使用 [Cloudflare Images 绑定](https://developers.cloudflare.com/images/transform-images/bindings/) 在运行时转换图像,该绑定会在你部署时自动配置。 -The default value of `imageService` has changed from `'compile'` to `'cloudflare-binding'` for an improved experience when working with images. +如果你希望恢复到以前的的模式(即图像转换仅在构建时对预渲染路由可用),请在适配器配置中设置 `imageService: 'compile'`。 -The `cloudflare-binding` service uses the [Cloudflare Images binding](https://developers.cloudflare.com/images/transform-images/bindings/) to transform images at runtime, and the binding is automatically provisioned when you deploy. +### 更改:部署到 Cloudflare 环境 -To revert to the previous behavior, where image transformation was only available on prerendered routes at build time, set `imageService: 'compile'` explicitly in your adapter config. +在 Astro 5.x 中,你可以一次性构建 Astro 项目,然后通过 `wrangler deploy --env some-env` 将其部署到特定的 Cloudflare 环境。 -### Changed: Deploy to Cloudflare Environment +从 Astro 6.0 开始,集成依赖于 Cloudflare Vite 插件,并且这一行为发生了变化。环境现在是在构建阶段确定的。因此,你必须为每个环境分别构建项目。 -In Astro 5.x, you could build your Astro project once and deploy it to a specific Cloudflare environment with `wrangler deploy --env some-env`. +要部署到特定的 Cloudflare 环境,请在命令前加上 `CLOUDFLARE_ENV` 变量。例如,`CLOUDFLARE_ENV=some-env astro build && wrangler deploy` 会构建你的 Astro 项目,并使用 `some-env` 环境通过 Wrangler 进行部署。 -Since Astro 6.0, the integration relies on the Cloudflare Vite plugin and this behavior has changed. The environment is now determined during the build phase. Therefore, you must build your project separately for each environment. +请参阅从 [wrangler dev 迁移指南](https://developers.cloudflare.com/workers/vite-plugin/reference/migrating-from-wrangler-dev/#cloudflare-environments)中的[Cloudflare 环境](https://developers.cloudflare.com/workers/vite-plugin/reference/cloudflare-environments/)部分,了解如何更新配置。 -To deploy to a specific Cloudflare environment, prefix your command with the `CLOUDFLARE_ENV` variable. For example, the command `CLOUDFLARE_ENV=some-env astro build && wrangler deploy` will build your Astro project and deploy it with Wrangler using the `some-env` environment. +[astro-integration]: /zh-cn/guides/integrations/ -Learn how to update your [Cloudflare environments](https://developers.cloudflare.com/workers/vite-plugin/reference/cloudflare-environments/) in the [Migrate from wrangler dev guide](https://developers.cloudflare.com/workers/vite-plugin/reference/migrating-from-wrangler-dev/#cloudflare-environments). -[astro-integration]: /en/guides/integrations/ From 7ab4d84dfa03e12b4816872efd1e9fd01fa64825 Mon Sep 17 00:00:00 2001 From: HakuRan Date: Sun, 7 Jun 2026 13:34:13 +0800 Subject: [PATCH 8/9] i18n(zh-cn): add cloudflare.mdx --- src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index 0211f65dde58a..36023a5b8b3e3 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -21,7 +21,7 @@ import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; 在我们的 [Cloudflare 部署指南](/zh-cn/guides/deploy/cloudflare/) 中学习如何部署你的 Astro 网站。 :::tip[更新到 Astro 6?] -Astro 6 需要将次适配器更新到 v13。 关于重大变更和迁移指南,请参阅 [针对 Astro 6 的 Cloudflare 适配器升级说明。](#upgrading-to-v13-and-astro-6) +Astro 6 需要将次适配器更新到 v13。 关于重大变更和迁移指南,请参阅 [针对 Astro 6 的 Cloudflare 适配器升级说明。](#升级到-v13-和-astro-6) ::: ## 为什么选择 Cloudflare? From 793629f72d114832db07747d66945d805f3df20f Mon Sep 17 00:00:00 2001 From: HakuRan Date: Wed, 10 Jun 2026 11:20:42 +0800 Subject: [PATCH 9/9] fix broken fragment link --- src/content/docs/zh-cn/guides/deploy/cloudflare.mdx | 2 +- src/content/docs/zh-cn/guides/environment-variables.mdx | 2 +- src/content/docs/zh-cn/guides/sessions.mdx | 2 +- src/content/docs/zh-cn/reference/configuration-reference.mdx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/zh-cn/guides/deploy/cloudflare.mdx b/src/content/docs/zh-cn/guides/deploy/cloudflare.mdx index 5a1f71126f5fe..bfb63ab2bc446 100644 --- a/src/content/docs/zh-cn/guides/deploy/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/deploy/cloudflare.mdx @@ -164,6 +164,6 @@ Cloudflare 更建议为新项目使用 Cloudflare Workers。对于现有的、 - 这意味着你在服务器端环境中使用的某个包或导入项与 [Cloudflare 运行时 API](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) 不兼容。 -- 如果你直接导入了一个 Node.js 运行时 API,请参考 Astro 关于 Cloudflare 的 [Node.js 兼容性](/zh-cn/guides/integrations-guide/cloudflare/#nodejs-compatibility) 文档,了解如何解决这个问题的进一步步骤。 +- 如果你直接导入了一个 Node.js 运行时 API,请参考 Astro 关于 Cloudflare 的 [Node.js 兼容性](/zh-cn/guides/integrations-guide/cloudflare/#nodejs-兼容性) 文档,了解如何解决这个问题的进一步步骤。 - 如果你导入的包中包含了 Node.js 运行时 API,请检查该包的作者是否支持 `node:*` 的导入语法。如果不支持,你可能需要找到一个替代的包。 diff --git a/src/content/docs/zh-cn/guides/environment-variables.mdx b/src/content/docs/zh-cn/guides/environment-variables.mdx index b16d12eb84b52..ca906e94a4f8a 100644 --- a/src/content/docs/zh-cn/guides/environment-variables.mdx +++ b/src/content/docs/zh-cn/guides/environment-variables.mdx @@ -188,7 +188,7 @@ const data = await db(import.meta.env.DB_PASSWORD); const data = fetch(`${import.meta.env.PUBLIC_POKEAPI}/pokemon/squirtle`); ``` -使用 SSR 时,可以根据所使用的 SSR 适配器,在运行时访问环境变量。对于大部分适配器,可以通过 `process.env` 访问环境变量,但有一些适配器在工作时有所不同。Deno 适配器则需要使用 `Deno.env.get()`。在使用 Cloudflare 适配器时,可以参阅如何 [访问 Cloudflare 运行时](/zh-cn/guides/integrations-guide/cloudflare/#cloudflare-runtime) 以处理环境变量。Astro 会检查服务器环境中的变量,如果这些变量不存在,则会在 `.env` 文件中查找它们。 +使用 SSR 时,可以根据所使用的 SSR 适配器,在运行时访问环境变量。对于大部分适配器,可以通过 `process.env` 访问环境变量,但有一些适配器在工作时有所不同。Deno 适配器则需要使用 `Deno.env.get()`。在使用 Cloudflare 适配器时,可以参阅如何 [访问 Cloudflare 运行时](/zh-cn/guides/integrations-guide/cloudflare/#cloudflare-运行时) 以处理环境变量。Astro 会检查服务器环境中的变量,如果这些变量不存在,则会在 `.env` 文件中查找它们。 ## 类型安全的环境变量 diff --git a/src/content/docs/zh-cn/guides/sessions.mdx b/src/content/docs/zh-cn/guides/sessions.mdx index 27f8b1b8b25d2..0fd675a2d8455 100644 --- a/src/content/docs/zh-cn/guides/sessions.mdx +++ b/src/content/docs/zh-cn/guides/sessions.mdx @@ -25,7 +25,7 @@ const cart = await Astro.session?.get('cart'); ## 配置会话 -会话需要一个存储驱动来将会话数据保存起来。[Node](/zh-cn/guides/integrations-guide/node/#sessions)、[Cloudflare](/zh-cn/guides/integrations-guide/cloudflare/#sessions) 和 [Netlify](/zh-cn/guides/integrations-guide/netlify/#sessions) 适配器都会为你自动配置默认的驱动,但是其他的适配器目前需要你 [手动指定驱动](/zh-cn/reference/configuration-reference/#sessiondriver) +会话需要一个存储驱动来将会话数据保存起来。[Node](/zh-cn/guides/integrations-guide/node/#sessions)、[Cloudflare](/zh-cn/guides/integrations-guide/cloudflare/#会话) 和 [Netlify](/zh-cn/guides/integrations-guide/netlify/#sessions) 适配器都会为你自动配置默认的驱动,但是其他的适配器目前需要你 [手动指定驱动](/zh-cn/reference/configuration-reference/#sessiondriver) ```js title="astro.config.mjs" ins={4} { diff --git a/src/content/docs/zh-cn/reference/configuration-reference.mdx b/src/content/docs/zh-cn/reference/configuration-reference.mdx index 2d10e52bc2293..8c9831fbd413f 100644 --- a/src/content/docs/zh-cn/reference/configuration-reference.mdx +++ b/src/content/docs/zh-cn/reference/configuration-reference.mdx @@ -839,7 +839,7 @@ export default defineConfig({

-Unstorage 上用于会话存储的驱动。[Node](/zh-cn/guides/integrations-guide/node/#sessions)、[Cloudflare](/zh-cn/guides/integrations-guide/cloudflare/#sessions) 和 [Netlify](/zh-cn/guides/integrations-guide/netlify/#sessions) 适配器都会为你自动配置默认的驱动,但是如果你更倾向于手动配置,或者是你正在使用的适配器并未提供驱动,你仍然可以自己指定。 +Unstorage 上用于会话存储的驱动。[Node](/zh-cn/guides/integrations-guide/node/#sessions)、[Cloudflare](/zh-cn/guides/integrations-guide/cloudflare/#会话) 和 [Netlify](/zh-cn/guides/integrations-guide/netlify/#sessions) 适配器都会为你自动配置默认的驱动,但是如果你更倾向于手动配置,或者是你正在使用的适配器并未提供驱动,你仍然可以自己指定。 该值为 [Unstorage 驱动文档](https://unstorage.unjs.io/drivers) 的“驱动名称(Driver name)”。