Astro JS - Configuration



The Astro Configuration File

The astro config file (/astro.config.mjs) is a javascript file included at root directory of every astro project. It is used to configure the Astro application such as setting up i18n routing, configuring redirects, and more. The astro config file is written in JavaScript and uses the .mjs file extension.

Syntax

Here is the syntax of an astro config file:

import { defineConfig } from "astro/config";

export default defineConfig({
    // your configuration options here...
});

Here is few examples of how to use an astro config file −

Configure Route Redirecting

Route redirecting is used to redirect users from one URL to another URL. You can specify the rules for redirects in the 'astro.config.mjs' file. The 'redirects' property in the config file is an array of objects that define the redirect rules.

// File: /astro.config.mjs

import { defineConfig } from 'astro/config';

export default defineConfig({
  redirects: {
    '/old-page': '/new-page',
    '/blog': 'https://example.com/blog'
  }
});

Configure i18n Routing

i18n routing is used to create internationalized routes in Astro. You can specify the rules for i18n routing in the 'astro.config.mjs' file. The 'i18n' property in the config file is an object that define the i18n routing rules.

// File: /astro.config.mjs

import { defineConfig } from "astro/config"
export default defineConfig({
  i18n: {
    locales: ["es", "en", "pt-br"],
    defaultLocale: "en",
  }
})

Configure Deployment Domain

The 'site' property in the astro config file is used to specify the domain name of the deployed site. This is useful for generating absolute URLs in your Astro application. Different deployment hosts may have different behavior regarding trailing slashes at the end of your URLs. (e.g. example.com/about vs example.com/about/). Once your site is deployed, you may need to configure your trailingSlash preference. See the example below.

// File: /astro.config.mjs

import { defineConfig } from "astro/config";

export default defineConfig({
  site: "https://www.example.com",
  base: "/docs",
  trailingSlash: "always",
});

TypeScript Configuration

Astro have inbuilt support for TypeScript for type checking, component development, and other static analysis tasks. The tsconfig.json file root directory is used to configure the TypeScript settings for an Astro project. With this file, you can specify how typescript should compiled, strictness levels, module resolution, and other options. Let's see an example of typescript configuration.

Example

The configuration below sets strict compiler options for TypeScript in an Astro project.

{
  "extends": "astro/tsconfigs/strictest",
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "node",
    "allowJs": true,
    "jsx": "preserve"
  }
}
Advertisements