Astroのドキュメント通りだと文字化けする
Astroの公式サイトには、Astroの使い方について書かれたドキュメントがあります。
このドキュメントの一部は日本語で書かれており、日本人ユーザーにも読みやすくなっています。
https://docs.astro.build/ja/getting-started
このドキュメントの中には「Astroページ」という項目があります。
https://docs.astro.build/ja/basics/astro-pages/#astro%E3%83%9A%E3%83%BC%E3%82%B8
Astroページのコードは以下のようになっています。
Astro
<html lang="ja">
<head>
<title>ホームページ</title>
</head>
<body>
<h1>私のホームページへようこそ!</h1>
</body>
</html>
しかし、「src/pages/index.astro」をドキュメントに書かれているとおりに修正して、npm run devを実行して確認すると以下の画像のように文字化けします。
Astroの開発環境は「npm create astro@latest」を実行後、「my-astro」のようなプロジェクトフォルダ名を入力し、すべて「Yes」を選択するだけで構築できます。
ShellScript
npm create astro@latest
astro Launch sequence initiated.
dir Where should we create your new project?
./my-astro
tmpl How would you like to start your new project?
Include sample files
ts Do you plan to write TypeScript?
Yes
use How strict should TypeScript be?
Strict
deps Install dependencies?
Yes
git Initialize a new git repository?
Yes
✔ Project initialized!
■ Template copied
■ TypeScript customized
■ Dependencies installed
■ Git initialized
next Liftoff confirmed. Explore your project!
インストールが完了したら、「src/pages/index.astro」を先述の方法でHTMLに修正すると、文字化けが確認されます。
Astroで文字化けが発生する原因
Astroで文字化けが発生する原因は文字コードがUTF-8になっていないからです。
そのため、<meta charset="UTF-8" />をheadタグ内に追加すれば解消されます。
HTML
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>ホームページ</title>
</head>
<body>
<h1>私のホームページへようこそ!</h1>
</body>
</html>
元は英語のドキュメントでは「My Homepage」なので、文字コードがUTF-8でなくても文字化けしませんが、日本語だと<meta charset="UTF-8" />がないと文字化けするので注意が必要です。