LoginSignup
5
4

More than 3 years have passed since last update.

コピペで始めるNext.js + Firebase Hosting 【静的サイト】

Last updated at Posted at 2020-03-22

概要

Next.jsで静的サイトをホスティングする手順

※この記事はさくっとデプロイまでの手順を記述しているだけなので、解説とかはありません。

Next.js公式

準備

firebase-toolsをインストールしておく
Firebase CLI リファレンス

Next.jsプロジェクトの作成

$ npm init <プロジェクト名>
$ cd <プロジェクト名>
$ npm install --save next react react-dom

package.jsonscriptsを追加する

package.json
"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start",
  "export": "next build && next export"
}

typescriptの導入

typescriptを使用しない場合は飛ばしてください

npm install --save-dev typescript @types/react @types/node

index.jsとabout.jsを作成

src/pages/index.js
const Home = () => {
  return <div>Home</div>;
};

export default Home;
src/pages/about.js
const About = () => {
  return <div>About</div>;
};

export default About;

firebaseの設定

$ firebase init
...
/* アプリをデプロイするだけなのでHostingのみでOK */
 ◯ Database: Deploy Firebase Realtime Database Rules
 ◯ Firestore: Deploy rules and create indexes for Firestore
 ◯ Functions: Configure and deploy Cloud Functions
❯◉ Hosting: Configure and deploy Firebase Hosting sites
 ◯ Storage: Deploy Cloud Storage security rules
/* 既存のFirebaseプロジェクトを指定するか、新しくプロジェクトを作る */
? Select a default Firebase project for this directory: 
  [don't setup a default project] 
❯ next-static-sample (next-static-sample) 
  [create a new project]
/* この辺の設定はお好きにどうぞ */
? What language would you like to use to write Cloud Functions? 
? Do you want to use TSLint to catch probable bugs and enforce style? (Y/n)
? Do you want to install dependencies with npm now?
? What do you want to use as your public directory?
? Configure as a single-page app (rewrite all urls to /index.html)? 

設定が終わると「.firebaserc」や「firebase.json」ファイルが生成されます。

以下のコマンドも入れておきましょう。
.firebasercで使用するプロジェクトを指定します。

$ firebase use default

※ 初期設定ではコンソールで設定したプロジェクトのみ存在していると思います。

firebase.jsonを以下のように変更

firebase.json
{
  "hosting": {
    "public": "out",
    "rewrites": [
      {
        "source": "/about",
        "destination": "/about.html"
      }
    ]
  }
}

src/pagesの中身を追加した際は、"rewrites"内の"about"のように追加していく

package.jsonscriptsに以下を追加する

package.json
"scripts": {
  "deploy": "firebase deploy"
}

デプロイ

ビルドしてデプロイ

$ npm run export
$ npm run deploy
5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4