BLOG

Astro備忘録【設定編】

Written by ogoe

INDEX

個人的によく使用するAstroの設定をまとめます。

バージョン

Astro5.11.0

サイトのURLを設定する、呼び出す

以下公式ドキュメントから引用

最終的にデプロイされるURLです。Astroはビルドの最後にのURLを生成するためにこの完全なURLを使用します。Astroを最大限活用するためにこの値を設定することを強く推奨します。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  site: 'https://evoworx.dev/',
});
index.astro
---
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const ogImageURL = new URL('/img/ogp.png', Astro.site);
---

<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={ogImageURL} /> <!-- https://evoworx.dev/img/ogp.png -->

ページとアセットのルートを設定する

設定したパスを基準にページとアセットのディレクトリが反映されます。
後述のtrailingSlashの影響を受けます。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  base: '/blog',
});

URL末尾のスラッシュの規則を決める

本番環境で末尾のスラッシュの有無を厳格に扱う場合に設定します。
設定すると開発環境でもスラッシュの有無によってURLの動作が変わります。

trailingSlash: 'always'

スラッシュを含む

trailingSlash: 'never'

スラッシュを含まない

trailingSlash: 'ignore'

こだわらない(デフォルト)

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  // trailingSlash: 'always', // /blog/ 🙆‍♂️
  // trailingSlash: 'never', // /blog 🙆‍♂️
  // trailingSlash: 'ignore', // /blog 🙆‍♂️, /blog/ 🙆‍♂️
});

ビルド結果を出力するディレクトリを変更する

絶対パスかプロジェクトルートからの相対パスを指定します。デフォルトは./distです。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  outDir: './htdocs',
});

ビルド結果をルート外に出力する

import.meta.dirnameで現在のファイルの絶対パスを取得します。
以下では現在のディレクトリから1つ上のディレクトリに移動し、htdocsディレクトリを出力先として設定しています。

astro.config.mjs
import { defineConfig } from 'astro/config';
import path from 'path';

const __dirname = import.meta.dirname; // 現在のファイルの絶対パス
const dist = path.join(__dirname, '..', 'htdocs'); // 出力先ディレクトリ

export default defineConfig({
  outDir: dist,
});

サイトマップを自動で生成する

公式が提供するAstro integrationの@astrojs/sitemapを使うとビルド時に自動でサイトマップが生成されます。
詳細はドキュメントを参照ください。

サイトを多言語対応させる

i18nのルーティング機能を使うと多言語対応ができます。
詳細はドキュメントを参照ください。

CSSのスコープ方式を:where()にする

scopedStyleStrategy'where'にすることでCSSのスコープに:where()を使用します。
Astro3.0からデフォルトでデータ属性を用いてスコープするようになりました。

scopedStyleStrategy: 'where'

:where()を使用

scopedStyleStrategy: 'class'

クラスを使用

scopedStyleStrategy: 'attribute'

データ属性を使用(デフォルト)

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  scopedStyleStrategy: 'where', // .title:where(.astro-000)
});

SCSSの関数やmixinをコンポーネント内で使用する

Viteの設定を上書きします。
使用したい関数やmixin、変数などをscssファイルにまとめます。

_mixin.scss
@mixin mediaQuery($breakpoint) {
  @media screen and (min-width: #{$breakpoint}px) {
    @content;
  }
}
astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "./src/styles/_mixin.scss" as mixin;`,
        },
      }.
    },
  },
});
index.astro
<style lang="scss">
  p {
    color: red;

    @include mixin.mq('1280') {
      color: blue;
    }
  }
</style>

ビルド結果のHTMLの圧縮を無効にする

compressHTMLfalseにすることでHTMLの圧縮を無効にできます。
Astro3.0からデフォルトでHTMLを圧縮するようになりました。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  compressHTML: false,
});

ビルド結果のページの出力形式を変更する

HTMLやディレクトリの構成を変更できます。
デフォルトではディレクトリが生成されます。

build.format: 'file'

ファイルを生成

build.format: 'directory'

ディレクトリを生成(デフォルト)

build.format: 'preserve'

ソースに合わせる

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  build: {
    // format: 'file', // '/foo.html'
    // format: 'directory' // '/foo/index.html'
    // format: 'preserve' // src/pages/about.astro => /about.html, src/pages/about/index.astro => /about/index.html
  },
});

ビルド結果のすべてのCSSをcssファイルに出力する

'never'にすることですべてのCSSがcssファイルに出力されます。
デフォルトではCSSの記述容量が少なければインラインで出力されます。

build.inlineStylesheets: 'always'

インライン

build.inlineStylesheets: 'auto'

4kb以下ならインライン、以上ならcssファイル(デフォルト)

build.inlineStylesheets: 'never'

cssファイル

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  build: {
    inlineStylesheets: 'never',
  },
});

ビルド結果のCSSをひとつのファイルにまとめる

Viteの設定を上書きします。
デフォルトでは分割されるのでひとまとめにします。

vite.build.cssCodeSplit: true

ファイルを分割(デフォルト)

vite.build.cssCodeSplit: false

ファイルをまとめる

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    build: {
      cssCodeSplit: false,
    },
  },
});

ビルド結果のJSやCSSのディレクトリやファイル名を指定する

Viteの設定を上書きします。
デフォルトではファイル名末尾にハッシュがつくのでもろとも変更します。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        output: {
          entryFileNames: (chunkInfo) => {
            const { facadeModuleId } = chunkInfo;
            const match = facadeModuleId?.toLowerCase().match(/\/([^\/]+)\.astro/);
            const fileName = match && match[1] ? `${match[1]}` : 'violation';
            return `js/${fileName}.js`;
          },
          assetFileNames: (assetInfo) => {
            const { names } = assetInfo;
            if (names[0].match(/\.css$/)) {
              return 'css/[name].[ext]';
            } else if (names[0].match(/\.(jpg|jpeg|png|gif|svg|ico|webp|avif)$/)) {
              return 'img/[name].[ext]';
            } else if (names[0].match(/\.(mp4|webm|mov|)$/)) {
              return 'video/[name].[ext]';
            } else if (names[0].match(/\.(woff|woff2|ttf|otf)$/)) {
              return 'font/[name].[ext]';
            } else {
              return 'common/[name].[ext]';
            }
          },
        },
      },
    },
  },
});

ビルド結果のリンクを相対パスに置き換える

Astro integrationのastro-relative-linksを使うとビルド時にリンクを相対パスに置き換えます。
詳細はドキュメントを参照ください。

開発環境をlocalhost以外にも表示する

サーバーが接続を受け付けるアドレスを設定します。
trueにすると、自分と同じネットワーク内の他端末からも開発環境にアクセスできます。

server.host: false

localhostのみ(デフォルト)

server.host: true

localhostと自分のIPアドレス

server.host: 'カスタムアドレス(string)'

localhostとカスタムアドレス

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  server: {
    // host: false,
    // host: true,
    // host: '192.168.x.x',
  },
});

開発環境のポート番号を変更する

開発環境を指定したポート番号で開きます。デフォルトは4321です。
設定したポートが使用されていた場合、Astroが利用可能な次のポート番号を自動で探します。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  server: {
    port: 1025,
  },
});

開発環境を起動したら自動でブラウザを立ち上げる

trueにすると起動時に自動でブラウザが立ち上がります。デフォルトはfalseです。
特定のページを開くこともできます。

astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  server: {
    // open: true, // 起動時に開発環境を自動でブラウザに表示する
    // open: '/about', // 起動時に開発環境の/aboutを自動でブラウザに表示する
  },
});

まとめ

astro.config.mjs
import { defineConfig } from 'astro/config';
import path from 'path';
// import sitemap from '@astrojs/sitemap';
// import relativeLinks from 'astro-relative-links';

const __dirname = import.meta.dirname; // 現在のファイルの絶対パス
const dist = path.join(__dirname, '..', 'htdocs'); // 出力先ディレクトリ

export default defineConfig({
  site: 'https://evoworx.dev/', // サイトのURL
  base: '/blog', // ページとアセットのルート
  trailingSlash: 'always', // URL末尾のスラッシュ判定(含む /blog/)
  outDir: dist, // ビルド結果を出力するディレクトリ
  integrations: [
    // sitemap(), // サイトマップ生成
    // relativeLinks(), // 相対パス変換
  ],
  scopedStyleStrategy: 'where', // CSSスコープ方式(:where())
  compressHTML: false, // HTMLの圧縮を無効にする
  i18n: {
    locales: ['ja'],
    defaultLocale: 'ja',
  }, // 多言語対応
  build: {
    // format: 'directory', // ビルド結果のページの出力形式
    inlineStylesheets: 'never', // すべてのCSSをcssファイルに出力する
    cssCodeSplit: false, // CSSをひとつのファイルにまとめる
  },
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "./src/styles/_mixin.scss" as mixin;`, // SCSSを使用する
        },
      }.
    },
    build: {
      rollupOptions: {
        output: {
          entryFileNames: (chunkInfo) => {
            const { facadeModuleId } = chunkInfo;
            const match = facadeModuleId?.toLowerCase().match(/\/([^\/]+)\.astro/);
            const fileName = match && match[1] ? `${match[1]}` : 'violation';
            return `js/${fileName}.js`;
          }, // jsファイルのディレクトリとファイル名
          assetFileNames: (assetInfo) => {
            const { names } = assetInfo;
            if (names[0].match(/\.css$/)) {
              return 'css/[name].[ext]';
            } else if (names[0].match(/\.(jpg|jpeg|png|gif|svg|ico|webp|avif)$/)) {
              return 'img/[name].[ext]';
            } else if (names[0].match(/\.(mp4|webm|mov|)$/)) {
              return 'video/[name].[ext]';
            } else if (names[0].match(/\.(woff|woff2|ttf|otf)$/)) {
              return 'font/[name].[ext]';
            } else {
              return 'common/[name].[ext]';
            }
          }, // アセット系ファイルのディレクトリとファイル名
        },
      },
    },
  },
  server: {
    host: true, // 開発環境をlocalhostと自分のIPアドレスから立ち上げる
    port: 1025, // 開発環境のポート番号
    open: true, // 起動時に開発環境を自動でブラウザに表示する
  },
});

参考

Getting started | Docs
dirname, filename を ES Modules で使う方法
Astro でリンクや参照などを相対パスでビルドする
ビルド後に組み込み作業アリ用のAstro開発環境