nextjsを始めてみる(インストールから起動して確認するまで)[Typescript]

nextjs

nextjsとは

nextjsは、reactベースに作られるJavascriptのフレームワークです。
また、reactとは大きく違う部分としては、フロントエンドだけでなくバックエンドのAPIについても同時に実装が可能なことです。

また、nextjsのrouterも決まった形式で作成するなどwebアプリケーションの開発に必要な機能が揃った便利なものです。

参照)公式サイト

インストール

インストールする場合は下記コマンドで作成できます

npx create-next-app@latest
# or
yarn create next-app
# or
npm create next-app

typescriptを使いたい場合は下記のように–typescriptオプションをつけます

npx create-next-app@latest --typescript
# or
yarn create next-app --typescript
# or
npm create next-app --typescript

今回は、typescriptを使いたいのでyarn create next-app –typescriptでインストールを行います

コマンドを入力するとプロジェクト名とESLintを使いたいかを聞かれるので任意に入力します(ESLintはスペースなどのフォーマットや構文でのバグがないかを解析してくれるツールです)

yarn create next-app --typescript
yarn create v1.22.18
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
[3/4] 🔗 Linking dependencies...
[4/4] 🔨 Building fresh packages...
warning Your current version of Yarn is out of date. The latest version is "1.22.19", while you're on "1.22.18".
info To upgrade, run the following command:
$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
success Installed "create-next-app@13.0.6" with binaries:
- create-next-app
✔ What is your project named? … my-app
✔ Would you like to use ESLint with this project? … No / Yes
Creating a new Next.js app in /Users/nishitakanori/git-directory/worktime/sample/my-app.

実行が完了すると入力したプロジェクト名でフォルダが作成され、その中にアプリケーションで必要なファイルが作成されます

完了したら、package.jsonにスクリプトが作成されているのでdevのコマンドで実行します

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
},

コマンド実行すると下記のようにコンソールに出力されます(下記のコマンドはyarnで実行しています)

$ yarn dev 
yarn run v1.22.18
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled client and server successfully in 921 ms (161 modules) 

コンソールに出力されているhttp://localhost:3000にアクセスすると下記画面が表示されれば正常にプロジェクトが作成されています。フロントエンド部分は/pages/index.tsxにあります。

次にバックエンドのAPI部分にアクセスしてみます。APIについては、http://localhost:3000/api/helloでブラウザで開いてみると下記のように{“name”:”John Doe”}とJson形式でレスポンスが返ってきます。これは、/pages/api/hello.tsに記述されている処理です

nextjsでのURlはpages直下からがURlになります。また、index.tsxなどindexのファイルを作るとディレクトリ名がURlになります。例えばpages/home/index.tsxとなっていればhttp://localhost:3000/homeがURLになります。

ディレクトリにindewx以外の名前があればその名前がURLになります。/pages/home/user.tsxとなっていればhttp://localhost:3000/home/userがURLになります。