- 起步
- 核心概念
- 教程
- 基础内容
- 内置功能
- 集成
- 操作指南
- 使用指南
- 配置
- 参考
- 社区资源
- 其他
- 为文档做出贡献
- 手动安装 Astro
- 升级到 Astro v4
- 升级到 Astro v3
- 升级到 Astro v2
- Legacy v0.x Upgrade Guide
- 从 Create React App(CRA)迁移
- 关于本教程
- 第一单元:前期准备
- 准备开发环境
- 创建你的第一个 Astro 项目
- 你的第一行 Astro 代码
- 创建在线代码仓库
- 将你的网站部署到网络
- 第二单元:页面
- 创建你的第一个 Astro 页面
- 编写你的第一篇 Markdown 博客文章
- 添加「关于你」的动态内容
- 给你的「关于」页面添加样式
- 应用全局样式
- 第三单元:组件
- 创建一个可重复使用的导航组件
- 创建社交媒体 footer
- 自己动手搭建导航 Header
- 编写你的第一个浏览器脚本
- 第四单元:布局
- 编写你的第一个布局
- 创建并传递数据到博客布局
- 布局结合,两全其美
- 第五单元 - Astro API
- 创建文章存档页
- 生成标签页面
- 编写标签索引页面
- 添加 RSS 订阅源
- 第六单元 - Astro 群岛
- 搭建你的第一个 Astro 岛屿
- 回到干燥的陆地。让你的博客从白天到黑夜,无需岛屿!
- 恭喜你!
- @astrojs/mdx
- 添加阅读时间
- 创建开发者工具栏应用
- @astrojs/alpinejs
- @astrojs/lit
- @astrojs/preact
- @astrojs/react
- @astrojs/solid-js
- @astrojs/svelte
- @astrojs/vue
- @astrojs/cloudflare
- @astrojs/netlify
- @astrojs/node
- @astrojs/vercel
- @astrojs/db
- @astrojs/markdoc
- @astrojs/partytown
- @astrojs/sitemap
- @astrojs/tailwind
- 使用流式处理来提升页面性能
- 从 Gatsby 迁移
- 从 Next.js 迁移
- 从 NuxtJS 迁移
- 从 Docusaurus 迁移到 Astro
- 从 Eleventy 迁移到 Astro
- 从 GitBook 迁移到 Astro
- 从Gridsome迁移到Astro
- 从 Hugo 迁移
- 从 Jekyll 迁移
- 从 Pelican 迁移
- 从 SvelteKit 迁移
- 从VuePress迁移
- 从 WordPress 迁移
- 状态共享
- Storyblok 与 Astro
- Contentful 与 Astro
- ButterCMS & Astro
- Builder.io & Astro
- Cosmic 与 Astro
- DatoCMS 与 Astro
- Front Matter CMS 与 Astro
- Ghost & Astro
- Hashnode & Astro
- Hygraph 与 Astro
- Keystatic & Astro
- Kontent.ai 与 Astro
- 无头模式的 Statamic 与 Astro
- Strapi 与 Astro
- Tina CMS 与 Astro
- Umbraco & Astro
- 无头(headless)模式的 WordPress 与 Astro
- ApostropheCMS 与 Astro
- Caisy & Astro
- CloudCannon与Astro
- Crystallize 与 Astro
- Decap CMS 与 Astro
- Directus 与 Astro
- KeystoneJS 与 Astro
- microCMS & Astro
- Payload CMS 与 Astro
- Prepr CMS & Astro
- Prismic & Astro
- Sanity & Astro
- Sitecore 体验管理器 & Astro
- Spinal & Astro
- 创作内容
- Firebase 与 Astro
- Supabase 与 Astro
- Turso 和 Astro
- Xata 与 Astro
- Appwrite & Astro
- 部署你的 Astro 站点至 Netlify
- 部署你的 Astro 站点至 Vercel
- 如何将你的 Astro 网站部署到 Deno
- 部署你的 Astro 站点至 GitHub Pages
- 部署你的 Astro 站点至 GitLab Pages
- 部署你的 Astro 站点至 Cloudflare Pages
- 将你的 Astro 网站部署到 AWS
- 将你的 Astro 网站通过 Flightcontrol 部署到 AWS
- 将你的 Astro 网站通过 SST 部署到 AWS
- 将你的 Astro 网站部署至 Google Cloud
- 部署你的 Astro 站点至 Google Firebase 托管
- 将你的 Astro 网站部署到 Heroku
- 将你的 Astro 网站部署到 Microsoft Azure
- 部署你的 Astro 站点至 Buddy
- 将你的 Astro 网站部署到 Edgio
- 将你的 Astro 站点部署到 Fly.io
- 将你的 Astro 网站部署到 Render
- 将你的 Astro 网站部署到 Stormkit
- 将你的 Astro 网站部署到 Surge
- 通过 Cleavr 部署你的 Astro 网站
- 将你的 Astro 站点部署到 Kinsta 应用托管
- 将你的 Astro 网站部署到 Space
- 将你的 Astro 站点部署到 Zeabur
- 将你的 Astro 网站部署到 Zerops
- 添加 RSS 摘要
- 安装一个 Vite 或 Rollup 插件
- 构建自定义图像组件
- 使用 API 路由构建表单
- 在 Astro 页面中构建 HTML 表单
- 在 Astro 中使用 Bun
- 调用服务器端点
- 校验验证码
- 用 Docker 来构建你的 Astro 网站
- 动态导入图片
- 为链接添加图标
- 添加 i18n 功能
- 添加最后修改时间
- 在 Astro 组件中共享状态
- 使用 Tailwind Typography 美化渲染后的 Markdown
- Unknown compiler error.
- Astro.redirect is not available in static mode.
- Astro.clientAddress is not available in current adapter.
- Astro.clientAddress cannot be used inside prerendered routes.
- Astro.clientAddress is not available in static mode.
- No static path found for requested path.
- Invalid type returned by Astro page.
- Missing value for client:media directive.
- No matching renderer found.
- No client entrypoint specified in renderer.
- Missing hint on client:only directive.
- Invalid value returned by a getStaticPaths path.
- Invalid entry inside getStaticPath's return value
- Invalid value returned by getStaticPaths.
- getStaticPaths RSS helper is not available anymore.
- Missing params property on getStaticPaths route.
- Invalid value for getStaticPaths route parameter.
- getStaticPaths() function required for dynamic routes.
- Invalid slot name.
- Cannot use Server-side Rendering without an adapter.
- No import found for component.
- Invalid prerender export.
- Invalid component arguments.
- Page number param not found.
- Image missing required "alt" property.
- Error while loading image service.
- Missing image dimensions
- Failed to retrieve remote image dimensions
- Unsupported image format
- Unsupported image conversion
- Prerendered dynamic endpoint has path collision.
- Expected src to be an image.
- Expected image options.
- Cannot set both densities and widths
- Image not found.
- Could not process image metadata.
- Image not found.
- Could not transform image.
- Unable to set response.
- The middleware didn't return a Response.
- The middleware returned something that is not a Response object.
- The endpoint did not return a Response.
- Value assigned to locals is not accepted.
- Astro.response.headers must not be reassigned.
- Can't load the middleware.
- Local images must be imported.
- Astro.glob() used outside of an Astro file.
- Astro.glob() did not match any files.
- A redirect must be given a location with the Location header.
- Invalid dynamic route.
- Could not find Sharp.
- Unknown Vite Error.
- Could not import file.
- Invalid glob pattern.
- Astro couldn't find the correct page to render
- The provided locale does not exist.
- Index page not found.
- You can't use the current function with the current strategy
- Prerendered routes aren't supported when internationalization domains are enabled.
- 启用了手动国际化路由但没有提供中间件。
- Astro can't render the route.
- Unhandled rejection
- i18n Not Enabled
- Route not found.
- Unknown CSS Error
- CSS Syntax Error
- Unknown Markdown Error.
- Failed to parse Markdown frontmatter.
- Invalid frontmatter injection.
- MDX integration missing.
- Unknown configuration error.
- Specified configuration file not found.
- Legacy configuration detected.
- Unknown CLI Error.
- Failed to generate content types.
- Unknown Content Collection Error.
- Content entry frontmatter does not match schema.
- Invalid content entry slug.
- Content Schema should not contain slug.
- Collection does not exist
- Content and data cannot be in same collection.
- Collection contains entries of a different type.
- Data collection entry failed to parse.
- Duplicate content entry slug.
- Actions must be used with server output.
- Unsupported transform in content config.
Legacy v0.x Upgrade Guide
This guide will help you upgrade through breaking changes in pre-v1 versions of Astro.
You can update your project’s version of Astro to the latest version using your package manager. If you’re using Astro integrations, you’ll also want to update those to the latest version.
- npm
- pnpm
- Yarn
# updates the astro dependency:
npm upgrade astro
# or, to update all dependencies:
npm upgrade
# updates the astro dependency:
pnpm upgrade astro
# or, to update all dependencies:
pnpm upgrade
# updates the astro dependency:
yarn upgrade astro
# or, to update all dependencies:
yarn upgrade
Read the guide below for major highlights and instructions on how to handle breaking changes.
Astro 1.0
Section titled Astro 1.0Astro v1.0 introduces some changes that you should be aware of when migrating from v0.x and v1.0-beta releases. See below for more details.
Updated: Vite 3
Section titled Updated: Vite 3Astro v1.0 has upgraded from Vite 2 to Vite 3. We’ve handled most of the upgrade for you inside of Astro; however, some subtle Vite behaviors may still change between versions. Refer to the official Vite Migration Guide if you run into trouble.
Deprecated: Astro.canonicalURL
Section titled Deprecated: Astro.canonicalURLYou can now use the new Astro.url
helper to construct your own canonical URL from the current page/request URL.
// Before:
const canonicalURL = Astro.canonicalURL;
// After:
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
Changed: Scoped CSS specificity
Section titled Changed: Scoped CSS specificitySpecificity will now be preserved in scoped CSS styles. This change will cause most scoped styles to happen to take precedence over global styles. But, this behavior is no longer explicitly guaranteed.
Technically, this is accomplished using the :where()
pseudo-class instead of using classes directly in Astro’s CSS output.
Let’s use the following style block in an Astro component as an example:
<style>
div { color: red; } /* 0-0-1 specificity */
</style>
Previously, Astro would transform this into the following CSS, which has a specificity of 0-1-1
— a higher specificity than the source CSS:
div.astro-XXXXXX { color: red; } /* 0-1-1 specificity */
Now, Astro wraps the class selector with :where()
, maintaining the authored specificity:
div:where(.astro-XXXXXX) { color: red; } /* 0-0-1 specificity */
The previous specificity increase made it hard to combine scoped styles in Astro with other CSS files or styling libraries (e.g. Tailwind, CSS Modules, Styled Components, Stitches). This change will allow Astro’s scoped styles to work consistently alongside them while still preserving the exclusive boundaries that prevent styles from applying outside the component.
Deprecated: Components and JSX in Markdown
Section titled Deprecated: Components and JSX in MarkdownAstro no longer supports components or JSX expressions in Markdown pages by default. For long-term support you should migrate to the @astrojs/mdx
integration.
To make migrating easier, a new legacy.astroFlavoredMarkdown
flag (removed in v2.0) can be used to re-enable previous Markdown features.
Converting existing .md
files to .mdx
Section titled Converting existing .md files to .mdxIf you’re not familiar with MDX, here are some steps you can follow to quickly convert an existing “Astro Flavored Markdown” file to MDX. As you learn more about MDX, feel free to explore other ways of writing your pages!
Install the
@astrojs/mdx
integration.Change your existing
.md
file extensions to.mdx
Remove any
src/pages/posts/my-post.mdxsetup:
properties from your frontmatter, and write any import statements below the frontmatter instead.--- layout: '../../layouts/BaseLayout.astro'setup: | import ReactCounter from '../../components/ReactCounter.jsx' title: 'Migrating to MDX' date: 2022-07-26 tags: ["markdown", "mdx", "astro"] ---import ReactCounter from '../../components/ReactCounter.jsx' # {frontmatter.title} Here is my counter component, working in MDX: <ReactCounter client:load />
Update any
Astro.glob()
statements that currently return.md
files so that they will now return your.mdx
files.Update any use of the
src/pages/index.astro<Content />
component to use the default export when importing MDX:
src/pages/index.astro--- // Multiple imports with Astro.glob const mdxPosts = await Astro.glob('./posts/*.mdx'); --- {mdxPosts.map(Post => <Post.default />)}
--- // Import a single page import { default as About } from './about.mdx'; --- <About />
<Markdown />
Component Removed
Section titled <Markdown /> Component RemovedAstro’s built-in <Markdown />
component has been moved to a separate package. To continue using this component, you will now need to install @astrojs/markdown-component
and update your imports accordingly. For more details, see the @astrojs/markdown
README.
Migrate to v1.0.0-beta
Section titled Migrate to v1.0.0-betaOn April 4, 2022 we released the Astro 1.0 Beta!
If you are coming from v0.25 or earlier, make sure you have read and followed the v0.26 Migration Guide below, which contained several major breaking changes.
The v1.0.0-beta.0
release of Astro contained no breaking changes. Below are small changes that were introduced during the beta period.
Changed: RSS Feeds
Section titled Changed: RSS FeedsRSS feeds should now be generated using the @astrojs/rss
package, as described in our RSS guide.
Migrate to v0.26
Section titled Migrate to v0.26New Configuration API
Section titled New Configuration APIOur Configuration API has been redesigned to solve a few glaring points of confusion that had built up over the last year. Most of the configuration options have just been moved or renamed, which will hopefully be a quick update for most users. A few options have been refactored more heavily, and may require a few additional changes:
.buildOptions.site
has been replaced with.site
(your deployed domain) and a new.base
(your deployed subpath) option..markdownOptions
has been replaced with.markdown
, a mostly similar config object with some small changes to simplify Markdown configuration..sitemap
has been moved into the @astrojs/sitemap integration.
If you run Astro with legacy configuration, you will see a warning with instructions on how to update. See our updated Configuration Reference for more information on upgrading.
Read RFC0019 for more background on these changes.
New Markdown API
Section titled New Markdown APIAstro v0.26 releases a brand new Markdown API for your content. This included three major user-facing changes:
- You can now
import
/import()
markdown content directly using an ESM import. - A new
Astro.glob()
API, for easier glob imports (especially for Markdown). - BREAKING CHANGE:
Astro.fetchContent()
has been removed and replaced byAstro.glob()
- BREAKING CHANGE: Markdown objects have an updated interface.
// v0.25let allPosts = Astro.fetchContent('./posts/*.md');
// v0.26+let allPosts = await Astro.glob('./posts/*.md');
When migrating, be careful about the new Markdown object interface. Frontmatter, for example, has been moved to the .frontmatter
property, so references like post.title
should change to post.frontmatter.title
.
This should solve many issues for Markdown users, including some nice performance boosts for larger sites.
Read RFC0017 for more background on these changes.
New Default Script Behavior
Section titled New Default Script Behavior<script>
tags in Astro components are now built, bundled and optimized by default. This completes a long-term move to make our Astro component syntax more consistent, matching the default-optimized behavior our <style>
tags have today.
This includes a few changes to be aware of:
- BREAKING:
<script hoist>
is the new default<script>
behavior. Thehoist
attribute has been removed. To use the new default behaviour, make sure there are no other attributes on the<script>
tag. For example, removetype="module"
if you were using it before. - New
<script is:inline>
directive, to revert a<script>
tag to previous default behavior (unbuilt, unbundled, untouched by Astro). - New
<style is:inline>
directive, to leave a style tag inline in the page template (similar to previous<script>
behavior). - New
<style is:global>
directive to replace<style global>
in a future release.
// v0.25<script hoist type="module">
// v0.26+<script>
Note that Astro will bundle this external script with the rest of your client-side JavaScript, and load it in the type="module"
script context. Some older JavaScript files may not be written for the module
context, in which case they may need to be updated to use this method.
How to Resolve Images & Other Assets
Section titled How to Resolve Images & Other Assets1. Absolute URL Path (Recommended)
Example: <img src="/penguin.png">
When to use this: If your asset lives inside of public/
.
If you place your images inside of public/
you can safely reference them by absolute URL path directly in your component templates. This is the simplest way to reference an asset that you can use today, and it is recommended for most users who are getting started with Astro.
2. ESM Import
Example: import imgUrl from './penguin.png'
When to use this: If your asset lives inside of the src/
directory, and you want automatic optimization features like filename hashing.
This works inside of any JavaScript or Astro component, and returns a resolved URL to the final image. Once you have the resolved URL, you can use it anywhere inside of the component template.
---
// Example: Astro will include this image file in your final build
import imgUrl from './penguin.png';
---
<img src={imgUrl} />
Similar to how Astro handles CSS, the ESM import allows Astro to perform some simple build optimizations for you automatically. For example, any asset inside of src/
that is imported using an ESM import (ex: import imgUrl from './penguin.png'
) will have its filename hashed automatically. This can let you cache the file more aggressively on the server, improving user performance. In the future, Astro may add more optimizations like this.
Tip: If you dislike static ESM imports, Astro also supports dynamic ESM imports. We only recommend this option if you prefer this syntax: <img src={(await import('./penguin.png')).default} />
.
Deprecated: <script>
Default Processing
Section titled Deprecated: <script> Default ProcessingPreviously, all <script>
elements were read from the final HTML output and processed + bundled automatically. This behavior is no longer the default. Starting in 0.24, you must opt-in to <script>
element processing via the hoist
attribute. The type="module"
is also required for hoisted modules.
<script>
// Will be rendered into the HTML exactly as written!
// ESM imports will not be resolved relative to the file.
</script>
<script type="module" hoist>
// Processed! Bundled! ESM imports work, even to npm packages.
</script>
Migrate to v0.23
Section titled Migrate to v0.23Missing Sass Error
Section titled Missing Sass ErrorPreprocessor dependency "sass" not found. Did you install it?
In our quest to reduce npm install size, we’ve moved Sass out to an optional dependency. If you use Sass in your project, you’ll want to make sure that you run npm install sass --save-dev
to save it as a dependency.
Deprecated: Unescaped HTML
Section titled Deprecated: Unescaped HTMLIn Astro v0.23+, unescaped HTML content in expressions is now deprecated. In future releases, content within expressions will have strings escaped to protect against unintended HTML injection.
<h1>{title}</h1> <!-- <h1>Hello <strong>World</strong></h1> --><h1>{title}</h1> <!-- <h1>Hello <strong>World</strong></h1> -->
To continue injecting unescaped HTML, you can now use set:html
.
<h1>{title}</h1><h1 set:html={title} />
To avoid a wrapper element, set:html
can work alongside <Fragment>
.
<h1>{title}!</h1><h1><Fragment set:html={title}>!</h1>
You can also protect against unintended HTML injection with set:text
.
<h1 set:text={title} /> <!-- <h1>Hello <strong>World</strong></h1> -->
Migrate to v0.21
Section titled Migrate to v0.21Vite
Section titled ViteStarting in v0.21, Astro is built with Vite. As a result, configurations written in snowpack.config.mjs
should be moved into astro.config.mjs
.
// @ts-check
/** @type {import('astro').AstroUserConfig} */
export default {
renderers: [],
vite: {
plugins: [],
},
};
To learn more about configuring Vite, please visit their configuration guide.
Vite Plugins
Section titled Vite PluginsIn Astro v0.21+, Vite plugins may be configured within astro.config.mjs
.
import { imagetools } from 'vite-imagetools';
export default { vite: { plugins: [imagetools()], },
};
To learn more about Vite plugins, please visit their plugin guide.
Vite Changes to Renderers
Section titled Vite Changes to RenderersIn Astro v0.21+, plugins should now use viteConfig()
.
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default {
name: '@astrojs/renderer-svelte',
client: './client.js',
server: './server.js', snowpackPlugin: '@snowpack/plugin-svelte', snowpackPluginOptions: { compilerOptions: { hydratable: true } }, viteConfig() { return { optimizeDeps: { include: ['@astrojs/renderer-svelte/client.js', 'svelte', 'svelte/internal'], exclude: ['@astrojs/renderer-svelte/server.js'], }, plugins: [ svelte({ emitCss: true, compilerOptions: { hydratable: true }, }), ], }; },
}
To learn more about Vite plugins, please visit their plugin guide.
Aliasing
Section titled AliasingIn Astro v0.21+, import aliases can be added from tsconfig.json
or jsconfig.json
.
{
"compilerOptions": {
"baseUrl": ".", "paths": { "@/components/*": ["src/components/*"] }
}
}
These aliases are integrated automatically into VSCode and other editors.
File Extensions in Imports
Section titled File Extensions in ImportsIn Astro v0.21+, files need to be referenced by their actual extension, exactly as it is on disk. In this example, Div.tsx
would need to be referenced as Div.tsx
, not Div.jsx
.
import Div from './Div.jsx' // Astro v0.20import Div from './Div.tsx' // Astro v0.21
This same change applies to a compile-to-css file like Div.scss
:
<link rel="stylesheet" href={Astro.resolve('./Div.css')}><link rel="stylesheet" href={Astro.resolve('./Div.scss')}>
Removed: Components in Frontmatter
Section titled Removed: Components in FrontmatterPreviously, you could create mini Astro Components inside of the Astro Frontmatter, using JSX syntax instead of Astro’s component syntax. This was always a bit of a hack, but in the new compiler it became impossible to support. We hope to re-introduce this feature in a future release of Astro using a different, non-JSX API.
To migrate to v0.21+, please convert all JSX Astro components (that is, any Astro components created inside of another component’s frontmatter) to standalone components.
Styling Changes
Section titled Styling ChangesAutoprefixer
Section titled AutoprefixerAutoprefixer is no longer run by default. To enable:
Install the latest version (
npm install autoprefixer
)Create a
postcss.config.cjs
file at the root of your project with:module.exports = { plugins: { autoprefixer: {}, }, };
Tailwind CSS
Section titled Tailwind CSSEnsure you have PostCSS installed. This was optional in previous releases, but is required now:
Install the latest version of postcss (
npm install -D postcss
)Create a
postcss.config.cjs
file at the root of your project with:module.exports = { plugins: { tailwindcss: {}, }, };
For more information, read the Tailwind CSS documentation
Known Issues
Section titled Known IssuesImports on top
Section titled Imports on topIn Astro v0.21+, a bug has been introduced that requires imports inside components to be at the top of your frontmatter.
---
import Component from '../components/Component.astro'
const whereShouldIPutMyImports = "on top!"
---
Upgrade Guides如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论