跳转到内容

Configuration Reference

此内容尚不支持你的语言。

The following reference covers all supported configuration options in Astro. To learn more about configuring Astro, read our guide on Configuring Astro.

astro.config.mjs
import { defineConfig } from 'astro/config'
export default defineConfig({
// your configuration options here...
})

Top-Level Options

root

Type: string
CLI: --root
Default: "." (current working directory)

You should only provide this option if you run the astro CLI commands in a directory other than the project root directory. Usually, this option is provided via the CLI instead of the Astro config file, since Astro needs to know your project root before it can locate your config file.

If you provide a relative path (ex: --root: './my-project') Astro will resolve it against your current working directory.

Examples

{
root: './my-project-directory'
}
Terminal window
$ astro build --root ./my-project-directory

srcDir

Type: string
Default: "./src"

Set the directory that Astro will read your site from.

The value can be either an absolute file system path or a path relative to the project root.

{
srcDir: './www'
}

publicDir

Type: string
Default: "./public"

Set the directory for your static assets. Files in this directory are served at / during dev and copied to your build directory during build. These files are always served or copied as-is, without transform or bundling.

The value can be either an absolute file system path or a path relative to the project root.

{
publicDir: './my-custom-publicDir-directory'
}

outDir

Type: string
Default: "./dist"

Set the directory that astro build writes your final build to.

The value can be either an absolute file system path or a path relative to the project root.

{
outDir: './my-custom-build-directory'
}

See Also:

  • build.server

cacheDir

Type: string
Default: "./node_modules/.astro"

Set the directory for caching build artifacts. Files in this directory will be used in subsequent builds to speed up the build time.

The value can be either an absolute file system path or a path relative to the project root.

{
cacheDir: './my-custom-cache-directory'
}

redirects

Type: Record.<string, RedirectConfig>
Default: {}

添加於: astro@2.9.0

Specify a mapping of redirects where the key is the route to match and the value is the path to redirect to.

You can redirect both static and dynamic routes, but only to the same kind of route. For example you cannot have a '/article': '/blog/[...slug]' redirect.

{
redirects: {
'/old': '/new',
'/blog/[...slug]': '/articles/[...slug]',
}
}

For statically-generated sites with no adapter installed, this will produce a client redirect using a <meta http-equiv="refresh"> tag and does not support status codes.

When using SSR or with a static adapter in output: static mode, status codes are supported. Astro will serve redirected GET requests with a status of 301 and use a status of 308 for any other request method.

You can customize the redirection status code using an object in the redirect config:

{
redirects: {
'/other': {
status: 302,
destination: '/place',
},
}
}

site

Type: string

Your final, deployed URL. Astro uses this full URL to generate your sitemap and canonical URLs in your final build. It is strongly recommended that you set this configuration to get the most out of Astro.

{
site: 'https://www.my-site.dev'
}

compressHTML

Type: boolean
Default: true

This is an option to minify your HTML output and reduce the size of your HTML files. By default, Astro removes all whitespace from your HTML, including line breaks, from .astro components. This occurs both in development mode and in the final build. To disable HTML compression, set the compressHTML flag to false.

{
compressHTML: false
}

base

Type: string

The base path to deploy to. Astro will use this path as the root for your pages and assets both in development and in production build.

In the example below, astro dev will start your server at /docs.

{
base: '/docs'
}

When using this option, all of your static asset imports and URLs should add the base as a prefix. You can access this value via import.meta.env.BASE_URL.

The value of import.meta.env.BASE_URL will be determined by your trailingSlash config, no matter what value you have set for base.

A trailing slash is always included if trailingSlash: "always" is set. If trailingSlash: "never" is set, BASE_URL will not include a trailing slash, even if base includes one.

Additionally, Astro will internally manipulate the configured value of config.base before making it available to integrations. The value of config.base as read by integrations will also be determined by your trailingSlash configuration in the same way.

In the example below, the values of import.meta.env.BASE_URL and config.base when processed will both be /docs:

{
base: '/docs/',
trailingSlash: "never"
}

In the example below, the values of import.meta.env.BASE_URL and config.base when processed will both be /docs/:

{
base: '/docs',
trailingSlash: "always"
}

trailingSlash

Type: 'always' | 'never' | 'ignore'
Default: 'ignore'

Set the route matching behavior of the dev server. Choose from the following options:

  • 'always' - Only match URLs that include a trailing slash (ex: “/foo/“)
  • 'never' - Never match URLs that include a trailing slash (ex: “/foo”)
  • 'ignore' - Match URLs regardless of whether a trailing ”/” exists

Use this configuration option if your production host has strict handling of how trailing slashes work or do not work.

You can also set this if you prefer to be more strict yourself, so that URLs with or without trailing slashes won’t work during development.

{
// Example: Require a trailing slash during development
trailingSlash: 'always'
}

See Also:

  • build.format

scopedStyleStrategy

Type: 'where' | 'class' | 'attribute'
Default: 'attribute'

添加於: astro@2.4

Specify the strategy used for scoping styles within Astro components. Choose from:

  • 'where' - Use :where selectors, causing no specificity increase.
  • 'class' - Use class-based selectors, causing a +1 specificity increase.
  • 'attribute' - Use data- attributes, causing a +1 specificity increase.

Using 'class' is helpful when you want to ensure that element selectors within an Astro component override global style defaults (e.g. from a global stylesheet). Using 'where' gives you more control over specificity, but requires that you use higher-specificity selectors, layers, and other tools to control which selectors are applied. Using 'attribute' is useful when you are manipulating the class attribute of elements and need to avoid conflicts between your own styling logic and Astro’s application of styles.

adapter

Type: AstroIntegration

Deploy to your favorite server, serverless, or edge host with build adapters. Import one of our first-party adapters for Netlify, Vercel, and more to engage Astro SSR.

See our Server-side Rendering guide for more on SSR, and our deployment guides for a complete list of hosts.

import netlify from '@astrojs/netlify/functions';
{
// Example: Build for Netlify serverless deployment
adapter: netlify(),
}

See Also:

  • output

output

Type: 'static' | 'server' | 'hybrid'
Default: 'static'

Specifies the output target for builds.

  • 'static' - Building a static site to be deploy to any static host.
  • 'server' - Building an app to be deployed to a host supporting SSR (server-side rendering).
  • 'hybrid' - Building a static site with a few server-side rendered pages.
import { defineConfig } from 'astro/config';
export default defineConfig({
output: 'static'
})

See Also:

  • adapter

Build Options

build.format

Type: ('file' | 'directory')
Default: 'directory'

Control the output file format of each page.

  • If 'file', Astro will generate an HTML file (ex: “/foo.html”) for each page.
  • If 'directory', Astro will generate a directory with a nested index.html file (ex: “/foo/index.html”) for each page.
{
build: {
// Example: Generate `page.html` instead of `page/index.html` during build.
format: 'file'
}
}

Effect on Astro.url

Setting build.format controls what Astro.url is set to during the build. When it is:

  • directory - The Astro.url.pathname will include a trailing slash to mimic folder behavior; ie /foo/.
  • file - The Astro.url.pathname will include .html; ie /foo.html.

This means that when you create relative URLs using new URL('./relative', Astro.url), you will get consistent behavior between dev and build.

To prevent inconsistencies with trailing slash behaviour in dev, you can restrict the trailingSlash option to 'always' or 'never' depending on your build format:

  • directory - Set trailingSlash: 'always'
  • file - Set trailingSlash: 'never'

build.client

Type: string
Default: './dist/client'

Controls the output directory of your client-side CSS and JavaScript when output: 'server' or output: 'hybrid' only. outDir controls where the code is built to.

This value is relative to the outDir.

{
output: 'server', // or 'hybrid'
build: {
client: './client'
}
}

build.server

Type: string
Default: './dist/server'

Controls the output directory of server JavaScript when building to SSR.

This value is relative to the outDir.

{
build: {
server: './server'
}
}

build.assets

Type: string
Default: '_astro'

添加於: astro@2.0.0

Specifies the directory in the build output where Astro-generated assets (bundled JS and CSS for example) should live.

{
build: {
assets: '_custom'
}
}

See Also:

  • outDir

build.assetsPrefix

Type: string
Default: undefined

添加於: astro@2.2.0

Specifies the prefix for Astro-generated asset links. This can be used if assets are served from a different domain than the current site.

For example, if this is set to https://cdn.example.com, assets will be fetched from https://cdn.example.com/_astro/... (regardless of the base option). You would need to upload the files in ./dist/_astro/ to https://cdn.example.com/_astro/ to serve the assets. The process varies depending on how the third-party domain is hosted. To rename the _astro path, specify a new directory in build.assets.

{
build: {
assetsPrefix: 'https://cdn.example.com'
}
}

build.serverEntry

Type: string
Default: 'entry.mjs'

Specifies the file name of the server entrypoint when building to SSR. This entrypoint is usually dependent on which host you are deploying to and will be set by your adapter for you.

Note that it is recommended that this file ends with .mjs so that the runtime detects that the file is a JavaScript module.

{
build: {
serverEntry: 'main.mjs'
}
}

build.redirects

Type: boolean
Default: true

添加於: astro@2.6.0

Specifies whether redirects will be output to HTML during the build. This option only applies to output: 'static' mode; in SSR redirects are treated the same as all responses.

This option is mostly meant to be used by adapters that have special configuration files for redirects and do not need/want HTML based redirects.

{
build: {
redirects: false
}
}

build.inlineStylesheets

Type: 'always' | 'auto' | 'never'
Default: auto

添加於: astro@2.6.0

Control whether project styles are sent to the browser in a separate css file or inlined into <style> tags. Choose from the following options:

  • 'always' - project styles are inlined into <style> tags
  • 'auto' - only stylesheets smaller than ViteConfig.build.assetsInlineLimit (default: 4kb) are inlined. Otherwise, project styles are sent in external stylesheets.
  • 'never' - project styles are sent in external stylesheets
{
build: {
inlineStylesheets: `never`,
},
}

build.split

Type: boolean
Default: false

The build config option build.split has been replaced by the adapter configuration option functionPerRoute.

Please see your SSR adapter’s documentation for using functionPerRoute to define how your SSR code is bundled.

build.excludeMiddleware

Type: boolean
Default: false

The build config option build.excludeMiddleware has been replaced by the adapter configuration option edgeMiddleware.

Please see your SSR adapter’s documentation for using edgeMiddleware to define whether or not any SSR middleware code will be bundled when built.

Prefetch Options

Type: boolean | object

Enable prefetching for links on your site to provide faster page transitions. (Enabled by default on pages using the <ViewTransitions /> router. Set prefetch: false to opt out of this behaviour.)

This configuration automatically adds a prefetch script to every page in the project giving you access to the data-astro-prefetch attribute. Add this attribute to any <a /> link on your page to enable prefetching for that page.

<a href="/about" data-astro-prefetch>About</a>

Further customize the default prefetching behavior using the prefetch.defaultStrategy and prefetch.prefetchAll options.

See the Prefetch guide for more information.

prefetch.prefetchAll

Type: boolean

Enable prefetching for all links, including those without the data-astro-prefetch attribute. This value defaults to true when using the <ViewTransitions /> router. Otherwise, the default value is false.

prefetch: {
prefetchAll: true
}

When set to true, you can disable prefetching individually by setting data-astro-prefetch="false" on any individual links.

<a href="/about" data-astro-prefetch="false">About</a>

prefetch.defaultStrategy

Type: 'tap' | 'hover' | 'viewport'
Default: 'hover'

The default prefetch strategy to use when the data-astro-prefetch attribute is set on a link with no value.

  • 'tap': Prefetch just before you click on the link.
  • 'hover': Prefetch when you hover over or focus on the link. (default)
  • 'viewport': Prefetch as the links enter the viewport.

You can override this default value and select a different strategy for any individual link by setting a value on the attribute.

<a href="/about" data-astro-prefetch="viewport">About</a>

Server Options

Customize the Astro dev server, used by both astro dev and astro preview.

{
server: { port: 1234, host: true}
}

To set different configuration based on the command run (“dev”, “preview”) a function can also be passed to this configuration option.

{
// Example: Use the function syntax to customize based on command
server: ({ command }) => ({ port: command === 'dev' ? 4321 : 4000 })
}

server.host

Type: string | boolean
Default: false

添加於: astro@0.24.0

Set which network IP addresses the server should listen on (i.e. non-localhost IPs).

  • false - do not expose on a network IP address
  • true - listen on all addresses, including LAN and public addresses
  • [custom-address] - expose on a network IP address at [custom-address] (ex: 192.168.0.1)

server.port

Type: number
Default: 4321

Set which port the server should listen on.

If the given port is already in use, Astro will automatically try the next available port.

{
server: { port: 8080 }
}

server.headers

Type: OutgoingHttpHeaders
Default: {}

添加於: astro@1.7.0

Set custom HTTP response headers to be sent in astro dev and astro preview.

Image Options

image.endpoint

Type: string
Default: undefined

添加於: astro@3.1.0

Set the endpoint to use for image optimization in dev and SSR. Set to undefined to use the default endpoint.

The endpoint will always be injected at /_image.

{
image: {
// Example: Use a custom image endpoint
endpoint: './src/image-endpoint.ts',
},
}

image.service

Type: Object
Default: {entrypoint: 'astro/assets/services/sharp', config?: {}}

添加於: astro@2.1.0

Set which image service is used for Astro’s assets support.

The value should be an object with an entrypoint for the image service to use and optionally, a config object to pass to the service.

The service entrypoint can be either one of the included services, or a third-party package.

{
image: {
// Example: Enable the Sharp-based image service
service: { entrypoint: 'astro/assets/services/sharp' },
},
}

image.domains

Type: Array.<string>
Default: {domains: []}

添加於: astro@2.10.10

Defines a list of permitted image source domains for remote image optimization. No other remote images will be optimized by Astro.

This option requires an array of individual domain names as strings. Wildcards are not permitted. Instead, use image.remotePatterns to define a list of allowed source URL patterns.

astro.config.mjs
{
image: {
// Example: Allow remote image optimization from a single domain
domains: ['astro.build'],
},
}

image.remotePatterns

Type: Array.<RemotePattern>
Default: {remotePatterns: []}

添加於: astro@2.10.10

Defines a list of permitted image source URL patterns for remote image optimization.

remotePatterns can be configured with four properties:

  1. protocol
  2. hostname
  3. port
  4. pathname
{
image: {
// Example: allow processing all images from your aws s3 bucket
remotePatterns: [{
protocol: 'https',
hostname: '**.amazonaws.com',
}],
},
}

You can use wildcards to define the permitted hostname and pathname values as described below. Otherwise, only the exact values provided will be configured: hostname:

  • Start with ’**.’ to allow all subdomains (‘endsWith’).
  • Start with ’*.’ to allow only one level of subdomain.

pathname:

  • End with ’/**’ to allow all sub-routes (‘startsWith’).
  • End with ’/*’ to allow only one level of sub-route.

Markdown Options

markdown.drafts

Type: boolean
Default: false

Control whether Markdown draft pages should be included in the build.

A Markdown page is considered a draft if it includes draft: true in its frontmatter. Draft pages are always included & visible during development (astro dev) but by default they will not be included in your final build.

{
markdown: {
// Example: Include all drafts in your final build
drafts: true,
}
}

markdown.shikiConfig

Type: Partial<ShikiConfig>

Shiki configuration options. See the Markdown configuration docs for usage.

markdown.syntaxHighlight

Type: 'shiki' | 'prism' | false
Default: shiki

Which syntax highlighter to use, if any.

  • shiki - use the Shiki highlighter
  • prism - use the Prism highlighter
  • false - do not apply syntax highlighting.
{
markdown: {
// Example: Switch to use prism for syntax highlighting in Markdown
syntaxHighlight: 'prism',
}
}

markdown.remarkPlugins

Type: RemarkPlugins

Pass remark plugins to customize how your Markdown is built. You can import and apply the plugin function (recommended), or pass the plugin name as a string.

import remarkToc from 'remark-toc';
{
markdown: {
remarkPlugins: [remarkToc]
}
}

markdown.rehypePlugins

Type: RehypePlugins

Pass rehype plugins to customize how your Markdown’s output HTML is processed. You can import and apply the plugin function (recommended), or pass the plugin name as a string.

import { rehypeAccessibleEmojis } from 'rehype-accessible-emojis';
{
markdown: {
rehypePlugins: [rehypeAccessibleEmojis]
}
}

markdown.gfm

Type: boolean
Default: true

添加於: astro@2.0.0

Astro uses GitHub-flavored Markdown by default. To disable this, set the gfm flag to false:

{
markdown: {
gfm: false,
}
}

markdown.smartypants

Type: boolean
Default: true

添加於: astro@2.0.0

Astro uses the SmartyPants formatter by default. To disable this, set the smartypants flag to false:

{
markdown: {
smartypants: false,
}
}

markdown.remarkRehype

Type: RemarkRehype

Pass options to remark-rehype.

{
markdown: {
// Example: Translate the footnotes text to another language, here are the default English values
remarkRehype: { footnoteLabel: "Footnotes", footnoteBackLabel: "Back to content"},
},
};

Integrations

Extend Astro with custom integrations. Integrations are your one-stop-shop for adding framework support (like Solid.js), new features (like sitemaps), and new libraries (like Partytown).

Read our Integrations Guide for help getting started with Astro Integrations.

import react from '@astrojs/react';
import tailwind from '@astrojs/tailwind';
{
// Example: Add React + Tailwind support to Astro
integrations: [react(), tailwind()]
}

Vite

Pass additional configuration options to Vite. Useful when Astro doesn’t support some advanced configuration that you may need.

View the full vite configuration object documentation on vitejs.dev.

Examples

{
vite: {
ssr: {
// Example: Force a broken package to skip SSR processing, if needed
external: ['broken-npm-package'],
}
}
}
{
vite: {
// Example: Add custom vite plugins directly to your Astro project
plugins: [myPlugin()],
}
}

Legacy Flags

To help some users migrate between versions of Astro, we occasionally introduce legacy flags. These flags allow you to opt in to some deprecated or otherwise outdated behavior of Astro in the latest version, so that you can continue to upgrade and take advantage of new Astro releases.

Experimental Flags

Astro offers experimental flags to give users early access to new features. These flags are not guaranteed to be stable.

experimental.optimizeHoistedScript

Type: boolean
Default: false

添加於: astro@2.10.4

Prevents unused components’ scripts from being included in a page unexpectedly. The optimization is best-effort and may inversely miss including the used scripts. Make sure to double-check your built pages before publishing. Enable hoisted script analysis optimization by adding the experimental flag:

{
experimental: {
optimizeHoistedScript: true,
},
}

experimental.devOverlay

Type: boolean
Default: false

添加於: astro@3.4.0

Enable a dev overlay in development mode. This overlay allows you to inspect your page islands, see helpful audits on performance and accessibility, and more.

{
experimental: {
devOverlay: true,
},
}

experimental.i18n

Type: object

添加於: astro@3.5.0

Configures experimental i18n routing and allows you to specify some customization options.

See our guide for more information on internationalization in Astro

experimental.i18n.defaultLocale

Type: string

添加於: astro@3.5.0

The default locale of your website/application. This is a required field.

No particular language format or syntax is enforced, but we suggest using lower-case and hyphens as needed (e.g. “es”, “pt-br”) for greatest compatibility.

experimental.i18n.locales

Type: Array.<string>

添加於: astro@3.5.0

A list of all locales supported by the website (e.g. ['en', 'es', 'pt-br']). This list should also include the defaultLocale. This is a required field.

No particular language format or syntax is enforced, but your folder structure must match exactly the locales in the list.

experimental.i18n.fallback

Type: Record.<string, string>

添加於: astro@3.5.0

The fallback strategy when navigating to pages that do not exist (e.g. a translated page has not been created).

Use this object to declare a fallback locale route for each language you support. If no fallback is specified, then unavailable pages will return a 404.

Example

The following example configures your content fallback strategy to redirect unavailable pages in /pt-br/ to their es version, and unavailable pages in /fr/ to their en version. Unavailable /es/ pages will return a 404.

export default defineConfig({
experimental: {
i18n: {
defaultLocale: "en",
locales: ["en", "fr", "pt-br", "es"],
fallback: {
pt: "es",
fr: "en"
}
}
}
})

experimental.i18n.routing

Type: Routing

添加於: astro@3.7.0

Controls the routing strategy to determine your site URLs. Set this based on your folder/URL path configuration for your default language.

experimental.i18n.routing.prefixDefaultLocale

Type: boolean
Default: false

添加於: astro@3.7.0

When false, only non-default languages will display a language prefix. The defaultLocale will not show a language prefix and content files do not exist in a localized folder. URLs will be of the form example.com/[locale]/content/ for all non-default languages, but example.com/content/ for the default locale.

When true, all URLs will display a language prefix. URLs will be of the form example.com/[locale]/content/ for every route, including the default language. Localized folders are used for every language, including the default.

experimental.contentCollectionCache

Type: boolean
Default: false

添加於: astro@3.5.0

Enables a persistent cache for content collections when building in static mode.

{
experimental: {
contentCollectionCache: true,
},
}