🌍

web制作環境にAstroを導入する

2023/07/21に公開

■経緯

reactかvueを使えば制作効率が上がりますが、ビルドしてできたファイルの中身は触るわけにはいかないので、更新・保守を行うのにreactかvueの知識を持ってる人に依存してしまうので手が出しづらい...という悩みをAstroが解決してくれました。

■Astroを導入

●Astroをインストール

Astroを入れたいディレクトリまで移動して、以下を実行する。

npm create astro@latest

下記内容の質問がくるので、質問に合わせて回答を選択してください。
※下記内容は全部エンターキー連チャンで押したので回答内容はあてにしなくてok。

Need to install the following packages:
  create-astro@3.1.10
Ok to proceed? (y) y
(node:3772) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

 astro   v2.8.3 Launch sequence initiated.

   dir   Where should we create your new project?
         ./bustling-binary

  tmpl   How would you like to start your new project?
         Include sample files
      ✔  Template copied

  deps   Install dependencies?
         Yes
      ✔  Dependencies installed

    ts   Do you plan to write TypeScript?
         Yes

   use   How strict should TypeScript be?
         Strict
      ✔  TypeScript customized

   git   Initialize a new git repository?
         Yes
      ✔  Git initialized

●開発サーバ起動

Astroを入れたらnpm run devを実行する。

npm run dev

http://localhost:3000 にアクセスすると、ローカルサーバーでトップページが表示されていることが確認できます。

http://localhost:3000

●VSCode拡張機能インストール

コードハイライトを効かせるため、VSCodeの拡張機能をインストールします。

■プラグインとビルドの設定

●astro-relative-linksを入れる

Astroは相対パスに対応していないので相対パスに対応するようにする。

npm i astro-relative-links

https://zenn.dev/ixkaito/articles/astro-relative-links
https://www.npmjs.com/package/astro-relative-links

●astro.config.mjsにプラグインとビルドの設定を入れる

自分が設定しているastro.config.mjsの内容は下記の通りです。
ビルドしたときにassetsフォルダの中にcss,images,js,fontがまとまるようにしています。

astro.config.mjs
import { defineConfig } from "astro/config";
import relativeLinks from 'astro-relative-links';

// https://astro.build/config
export default defineConfig({
  base: "",
  outDir: './dist',
  build: {
    format: 'file'
  },
  server: {
    // 開発サーバーが立ち上がったらブラウザを自動で開かせる
    open: true
  },
  integrations: [relativeLinks()],
  compressHTML: false,
  vite: {
    build: {
      minify: true,
      rollupOptions: {
        output: {
          assetFileNames: assetInfo => {
            let extType = assetInfo.name.split('.')[1];
            if (/ttf|otf|eot|woff|woff2/i.test(extType)) {
              extType = 'fonts';
            }
            if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {
              extType = 'images';
            }
            if (extType === 'css') {
              return `assets/css/style.css`;
            }
            return `assets/${extType}/[name][extname]`;
          }
        },
        entryFileNames: 'assets/js/[name].js'
      },
    },
  }
});

pagesフォルダ内にabout.astroを作成した場合、ビルドするとabout/index.htmlの形で出力するのですが、下記内容のものを指定するとabout.htmlで出力してくれます。

  build: {
    format: 'file',
  },

compressHTML: falseでhtmlをminifyしないようにしています。
buildしてできたhtmlファイルの中身をminifyしたい場合はここをtrueにしてください。

  compressHTML: false,

■Layout.astroの設定

●scssを導入する

以下のコマンドでscssをインストールします。

npm install -D sass

scssフォルダを作成する。

srcフォルダの直下にscssフォルダを作成し、scssフォルダの中にstyle.scssファイルを作成します。

※scssファイルの読み込みは一旦、置いといて次に行きます。

●コンポーネントを導入する

ヘッダーとフッターコンポーネントを作成する

src/componentsフォルダ内にHeader.astroとFooter.astroの2つのファイルを作成します。

●scssとコンポーネントを読み込む

src/layouts/Layout.astroでscssファイルとコンポーネントを下記のように読み込みます。
これでヘッダーコンテンツはHeader.astroにフッターのコンテンツはFooter.astroに記述していけばOK。

src/layouts/Layout.astro
---
/* コンポーネント */
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
/* scss */
import '../scss/style.scss';

const { title } = Astro.props;
---

<!DOCTYPE html>
<html lang="jp">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width" />
		<link rel="icon" type="image/svg+xml" href="favicon.svg" />
		<title>{title}</title>
		<meta name="description" content="Astro description">
		<meta property="og:image" content="サムネイル画像の URL" />
		<script type="module" src="./assets/js/common.js"></script>
	</head>
	<Header />
	<body>
		<slot />
	</body>
	<Footer />
</html>

■tailwind.css

tailwind.cssを導入します。
不要なら飛ばしてok。

●tailwind.cssを入れる

下記コマンドを実行する。

npm install postcss autoprefixer tailwindcss

postcss.config.cjsファイルを作成する

astro.config.mjsやpackage.jsonが置いてある階層にpostcss.config.cjsファイルを作成する。

postcss.config.cjs
module.exports = {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    }
}

tailwind.config.jsファイルを作成するファイルを作成する

postcss.config.cjsと同じようにtailwind.config.jsファイルを作成する。
tailwind.config.jsの中身は下記内容をそのままコピー貼り付けでOK。
pagesフォルダとcomponentsフォルダのastroファイルにtailwind.cssが反映されるようにしています。

tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
    content: ["./src/pages/*.astro","./src/components/*.astro"],
    theme: {
      extend: {},
    },
    plugins: [],
};

scssファイルにtalwind.cssを読み込む

scss/style.scss
@tailwind base;
@tailwind components;
@tailwind utilities;

これでtailwind.cssが使えるようになります。
↓自分がお世話になっているtailwind.cssのチートシート。
https://nerdcave.com/tailwind-cheat-sheet

astroが用意している@astrojs/tailwindで簡単にtailwind.cssを導入できますが、
astro.config.mjsのビルドの設定と競合して自分の環境で使えなかったので今回は使用しませんでした。
↓公式ドキュメント
https://docs.astro.build/ja/guides/integrations-guide/tailwind/

■images、js、fontファイルの格納場所

publicフォルダ内にassetsフォルダを作ってその中で各フォルダを作成する。

■実際にコーディングする

●Layout.astro読み込む

実際にコーディングするときのメインコンテンツの基本的な形は下記のようになります。
冒頭でLayout.astroを読み込みます。

src/pages/index.html
---
import Layout from "../layouts/Layout.astro";
---

<Layout title="page title">
  <main>
    <p>
      index.astro
    </p>
  </main>
</Layout>

●ページタイトルを設定する

titleに入れた文字列がLayout.astroの{title}に入ります。
各ページここでtitleの設定をしてください。

title="page title"

■ビルドする

npm run buildでビルドします。

npm run build

npm run buildをするとdistフォルダができあがるので、中身が下記画像のような内容になっていれば成功です。(多分)

■まとめ

以上がAstroの環境構築になります。
色々便利なプラグインがありましたが、assetsフォルダに出力することに拘るとなかなか取り入れることができませんでした。
まだまだカスタムできそうですが、一旦ここまで。

Discussion