---

title: 最小の Next.js + Bootstrapアプリを作成する
date: 2023-02-05
description: サーバーサイド寄りのエンジニアが管理画面をちゃちゃっと作るために最小限の Next.jsプロジェクトを作成する手順をまとめた
tweet_url: https://twitter.com/shimariso/status/1622237120302837760
image: nextjs-bootstrap.png
---
## 口上

何らかのサービスの管理画面的な物を作る。Next.jsというのを使ってみたい。でもフロントエンドのことは正直わからんし苦労して追いついてもどうせまた置いて行かれるのでなるべく Bootstrapの知識だけでなんとか切り抜けたい。

## ファイル構成

自分で作る最小限のファイルは下記の通り。

- package.json
- .gitignore
- pages/
    - index.tsx
    - _app.tsx
    - _document.tsx

その他、favicon.ico や画像などの静的リソースは public 以下、スタイルシートは styles 以下に配置する。

## package.jsonファイルの作成
```json
{
	"scripts":{
		"dev":"next dev",
		"build":"next build",
		"start":"next start"
	},
	"dependencies":{
	},
	"devDependencies":{
	}
}
```

## .gitignore ファイルの作成
```text
/.vscode
/node_modules
/.next/
next-env.d.ts
```

## npmモジュールのインストール

```sh
npm install --save next bootstrap react-bootstrap swr
```

### 各モジュールの雑な紹介

- [Next.js](https://nextjs.org/) - フロントエンドにReactを使ったWebアプリケーションフレームワーク
- [Bootstrap](https://getbootstrap.com/) - 管理画面作りマン用CSS
- [React Bootstrap](https://react-bootstrap.github.io/) - Reactで Bootstrapを使うためのもの
- [swr](https://swr.vercel.app/ja) - サーバ側APIと通信するためのライブラリ

## 最小Webアプリの作成

```sh
mkdir pages
```

### pages/_app.tsx

ここで bootstrap.min.cssをインポートしておくとすべてのページで Bootstrapのスタイルが使えるようになる。
[公式ドキュメント(Custom App)](https://nextjs.org/docs/advanced-features/custom-app)

```typescript
import type { AppProps } from 'next/app'
import Head from 'next/head'
import 'bootstrap/dist/css/bootstrap.min.css'

export default function MyApp({ Component, pageProps }: AppProps) {
  return <>
    <Head>
      <title>default title here</title>
    </Head>
    <Component {...pageProps} />
  </>
}
```

### pages/_document.tsx

すべてのページに共通の「外枠」をここでカスタマイズできる。
[Custom Document](https://nextjs.org/docs/advanced-features/custom-document)

ただし[ここでは Headの中に titleを入れられない](https://nextjs.org/docs/messages/no-document-title)ので代わりに _app.tsxのほうに入れること

```typescript
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="ja">
      <Head />
      <body>
        <div className="container">
            <Main />
        </div>
        <NextScript />
      </body>
    </Html>
  )
}
```

### pages/index.tsx

トップページを表現する tsx

```typescript
import Head from 'next/head'
import { Button } from 'react-bootstrap';

export default function Home() {
  return <>
    <Head>
      <title>My next.js + bootstrap webapp</title>
    </Head>
    <main>
      <h1>Hello, World!</h1>
      <Button>ボタンです</Button>
    </main>
  </>
}
```

## 実行

### 開発モードでの実行

```sh
npm run dev
```

3000番ポートで HTTPアクセスできる。ソースに対して変更を行うとブラウザ側も自動でリロードしてくれるなど大変親切。


### ビルドしてプロダクションモードで実行

```sh
npm run build
npm run start
```

3000番ポートで HTTPアクセスできる。nginxなどのWebサーバを前面に置いてリバースProxyするなどして運用しよう。

## その他情報

- ページ内で使用するプロパティをサーバ側で収集するにはそのページのソースで getServerSideProps という関数を exportする
