NEXT.jsのチュートリアル(Vercelでデプロイするまで)②TypeScriptに書き換え~デプロイ

[前回からの続き](https://qiita.com/MPrg2011/item/1bb02f98f33e05c6496b)です。

https://qiita.com/MPrg2011/item/1bb02f98f33e05c6496b

こちらを参照しました。

https://nextjs.org/learn/excel/typescript

---

## TypeScriptのインストール

1. ディレクトリ内でtscofig.jsonを作成
    
    ```bash
    touch tsconfig.json
    ```
    
    リスタート
    
    ```bash
    npm run dev
    ```
    
2. TypeScriptをインストール(npmにしました。yarnでも可)
    
    ```bash
    % npm install --save-dev typescript @types/react @types/node 
    
    added 8 packages, removed 9 packages, changed 4 packages, and audited 178 packages in 24s
    
    73 packages are looking for funding
      run `npm fund` for details
    
    found 0 vulnerabilities
    ```
    

### 変更になるところ

1. Static Generation(静的サイト生成) と Server-side Rendering(サーバーサイドレンダリング)
    
    `[getStaticProps](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation)`⇒`GetStaticProps`
    
    `[getStaticPaths](https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation)`⇒`GetStaticPaths`
    
    `[getServerSideProps](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering)`⇒`GetServerSideProps`
    
2. Appのカスタマイズ
    
    `pages/_app.js`を`pages/_app.tsx`に変換し、built-in type(プリミティブ型) `AppProps`を使用
    

## `.js` ⇒`.tsx` に変換

以下のファイルを全部`.tsx` に書き換え

- date.js
- layout.js
- posts.js
- [id].js
- index.js
- _app.js
- hello.js

commitはこんな感じ。

`next-env.d.ts` は自動的に生成されるようです。

![スクリーンショット_2022-03-20_20.15.18.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/a0c070e6-dde8-cd33-b748-86254a8e1f2b.png)

<details><summary>書き換えの途中のログ(node)</summary>

    % npm run dev
    
    > dev
    > next
    
    ready - started server on 0.0.0.0:3000, url: http://localhost:3000
    event - compiled client and server successfully in 2.8s (124 modules)
    wait  - compiling / (client and server)...
    event - compiled client and server successfully in 1439 ms (450 modules)
    wait  - compiling...
    error - ./components/date.js
    Error: Failed to read source code from /Users/mkk/Programming/Practice/nextjs-blog/components/date.js
    
    Caused by:
        No such file or directory (os error 2)
    wait  - compiling...
    error - ./components/date.js
    Error: Failed to read source code from /Users/mkk/Programming/Practice/nextjs-blog/components/date.js
    
    wait  - compiling...
    event - compiled successfully in 6484.2s (98 modules)
    wait  - compiling / (client and server)...
    error - ./pages/index.tsx:2:0
    Module not found: Can't resolve '../components/layout'
      1 | import Head from 'next/head'
    > 2 | import Layout, { siteTitle } from '../components/layout'
      3 | import utilStyles from '../styles/utils.module.css'
      4 | import { getSortedPostsData } from '../lib/posts'
      5 | import Link from 'next/link'
    
    https://nextjs.org/docs/messages/module-not-found                      
</details>        

### 再起動します

```bash
% npm run dev

> dev
> next

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
We detected TypeScript in your project and created a tsconfig.json file for you.
```

`We detected TypeScript in your project and created a tsconfig.json file for you.`は

tscongig.jsonがないから作ったよ、みたいな感じでした([最初に作ったつもり](https://qiita.com/MPrg2011/item/1bb02f98f33e05c6496b)でしたがタイポミスってた)

### Vercelで引っかかる

![スクリーンショット_2022-03-20_20.30.26.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/12e488bf-d15b-48db-c90c-3fbbb8848b76.png)

hello.tsxのディレクトリを間違えていた( ✕posts直下、○posts/api )ので、変更して再度コミット・プッシュ

![スクリーンショット_2022-03-20_20.34.08.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/da218947-c0cd-a4bb-38a5-4d5fa9c96673.png)
![スクリーンショット_2022-03-20_20.38.05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/ed50c613-dcc6-a60c-3bf5-7e6bcaf846bd.png)


Mergeできました！

![スクリーンショット_2022-03-20_20.43.41.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/2f6ac351-5ccb-51e6-5d83-55ee15f6b1cf.png)

## ESLintも導入してみた

1. package.jsonを編集
    
    ```bash
    {
      "private": true,
      "scripts": {
        "dev": "next",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
      },
    中略
    }
    ```
    
2. yarnでインストール
    
    ```bash
    % yarn lint
    yarn run v1.22.15
    $ next lint
    ? How would you like to configure ESLint? 
    ❯   Base configuration + Core Web Vitals rule-set (recommended)
        Base configuration
        None
    ```
    
    recommendedでEnterキー押すとインストール開始
    
<details><summary>ログ</summary>

        Installing devDependencies:
        - eslint
        - eslint-config-next
        
        warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.
        [1/4] 🔍  Resolving packages...
        [2/4] 🚚  Fetching packages...
        info @next/swc-linux-x64-gnu@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-linux-x64-gnu@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-win32-ia32-msvc@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-win32-ia32-msvc@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-win32-ia32-msvc@12.1.0: The CPU architecture "x64" is incompatible with this module.
        info @next/swc-linux-arm-gnueabihf@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-linux-arm-gnueabihf@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-linux-arm-gnueabihf@12.1.0: The CPU architecture "x64" is incompatible with this module.
        info @next/swc-win32-arm64-msvc@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-win32-arm64-msvc@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-win32-arm64-msvc@12.1.0: The CPU architecture "x64" is incompatible with this module.
        info @next/swc-linux-x64-musl@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-linux-x64-musl@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-linux-arm64-musl@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-linux-arm64-musl@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-linux-arm64-musl@12.1.0: The CPU architecture "x64" is incompatible with this module.
        info @next/swc-darwin-arm64@12.1.0: The CPU architecture "x64" is incompatible with this module.
        info "@next/swc-darwin-arm64@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-win32-x64-msvc@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-win32-x64-msvc@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-android-arm64@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-android-arm64@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-android-arm64@12.1.0: The CPU architecture "x64" is incompatible with this module.
        info @next/swc-linux-arm64-gnu@12.1.0: The platform "darwin" is incompatible with this module.
        info "@next/swc-linux-arm64-gnu@12.1.0" is an optional dependency and failed compatibility check. Excluding it from installation.
        info @next/swc-linux-arm64-gnu@12.1.0: The CPU architecture "x64" is incompatible with this module.
        [3/4] 🔗  Linking dependencies...
        [4/4] 🔨  Building fresh packages...
        success Saved lockfile.
        success Saved 148 new dependencies.
        info Direct dependencies
        ├─ eslint-config-next@12.1.0
        └─ eslint@8.11.0
        info All dependencies
        ├─ @babel/runtime-corejs3@7.17.8
        ├─ @babel/runtime@7.17.8
        ├─ @eslint/eslintrc@1.2.1
        ├─ @humanwhocodes/config-array@0.9.5
        ├─ @humanwhocodes/object-schema@1.2.1
        ├─ @next/eslint-plugin-next@12.1.0
        ├─ @nodelib/fs.scandir@2.1.5
        ├─ @nodelib/fs.stat@2.0.5
        ├─ @nodelib/fs.walk@1.2.8
        ├─ @rushstack/eslint-patch@1.1.1
        ├─ @types/json5@0.0.29
        ├─ @typescript-eslint/parser@5.15.0
        ├─ @typescript-eslint/scope-manager@5.15.0
        ├─ @typescript-eslint/typescript-estree@5.15.0
        ├─ acorn-jsx@5.3.2
        ├─ acorn@8.7.0
        ├─ ajv@6.12.6
        ├─ ansi-styles@4.3.0
        ├─ argparse@2.0.1
        ├─ aria-query@4.2.2
        ├─ array-includes@3.1.4
        ├─ array-union@2.1.0
        ├─ array.prototype.flat@1.2.5
        ├─ array.prototype.flatmap@1.2.5
        ├─ ast-types-flow@0.0.7
        ├─ axe-core@4.4.1
        ├─ axobject-query@2.2.0
        ├─ balanced-match@1.0.2
        ├─ brace-expansion@1.1.11
        ├─ braces@3.0.2
        ├─ callsites@3.1.0
        ├─ chalk@4.1.2
        ├─ concat-map@0.0.1
        ├─ core-js-pure@3.21.1
        ├─ cross-spawn@7.0.3
        ├─ damerau-levenshtein@1.0.8
        ├─ deep-is@0.1.4
        ├─ dir-glob@3.0.1
        ├─ emoji-regex@9.2.2
        ├─ es-to-primitive@1.2.1
        ├─ escape-string-regexp@4.0.0
        ├─ eslint-config-next@12.1.0
        ├─ eslint-import-resolver-node@0.3.6
        ├─ eslint-import-resolver-typescript@2.5.0
        ├─ eslint-module-utils@2.7.3
        ├─ eslint-plugin-import@2.25.4
        ├─ eslint-plugin-jsx-a11y@6.5.1
        ├─ eslint-plugin-react-hooks@4.3.0
        ├─ eslint-plugin-react@7.29.4
        ├─ eslint-scope@7.1.1
        ├─ eslint-utils@3.0.0
        ├─ eslint-visitor-keys@3.3.0
        ├─ eslint@8.11.0
        ├─ esquery@1.4.0
        ├─ esrecurse@4.3.0
        ├─ estraverse@5.3.0
        ├─ fast-deep-equal@3.1.3
        ├─ fast-glob@3.2.11
        ├─ fast-json-stable-stringify@2.1.0
        ├─ fast-levenshtein@2.0.6
        ├─ fastq@1.13.0
        ├─ file-entry-cache@6.0.1
        ├─ fill-range@7.0.1
        ├─ find-up@2.1.0
        ├─ flat-cache@3.0.4
        ├─ flatted@3.2.5
        ├─ functional-red-black-tree@1.0.1
        ├─ get-symbol-description@1.0.0
        ├─ glob-parent@6.0.2
        ├─ glob@7.2.0
        ├─ globals@13.13.0
        ├─ globby@11.1.0
        ├─ has-flag@4.0.0
        ├─ import-fresh@3.3.0
        ├─ imurmurhash@0.1.4
        ├─ is-bigint@1.0.4
        ├─ is-boolean-object@1.1.2
        ├─ is-callable@1.2.4
        ├─ is-core-module@2.8.1
        ├─ is-date-object@1.0.5
        ├─ is-extglob@2.1.1
        ├─ is-negative-zero@2.0.2
        ├─ is-number-object@1.0.6
        ├─ is-number@7.0.0
        ├─ is-regex@1.1.4
        ├─ is-shared-array-buffer@1.0.1
        ├─ is-string@1.0.7
        ├─ is-symbol@1.0.4
        ├─ is-weakref@1.0.2
        ├─ isexe@2.0.0
        ├─ json-schema-traverse@0.4.1
        ├─ json-stable-stringify-without-jsonify@1.0.1
        ├─ json5@1.0.1
        ├─ jsx-ast-utils@3.2.1
        ├─ language-subtag-registry@0.3.21
        ├─ language-tags@1.0.5
        ├─ locate-path@2.0.0
        ├─ lodash.merge@4.6.2
        ├─ merge2@1.4.1
        ├─ micromatch@4.0.4
        ├─ natural-compare@1.4.0
        ├─ object-inspect@1.12.0
        ├─ object.entries@1.1.5
        ├─ object.fromentries@2.0.5
        ├─ object.hasown@1.1.0
        ├─ optionator@0.9.1
        ├─ p-limit@1.3.0
        ├─ p-locate@2.0.0
        ├─ p-try@1.0.0
        ├─ parent-module@1.0.1
        ├─ path-exists@3.0.0
        ├─ path-key@3.1.1
        ├─ path-parse@1.0.7
        ├─ path-type@4.0.0
        ├─ picomatch@2.3.1
        ├─ prop-types@15.8.1
        ├─ punycode@2.1.1
        ├─ queue-microtask@1.2.3
        ├─ react-is@16.13.1
        ├─ regexp.prototype.flags@1.4.1
        ├─ regexpp@3.2.0
        ├─ resolve-from@4.0.0
        ├─ reusify@1.0.4
        ├─ rimraf@3.0.2
        ├─ run-parallel@1.2.0
        ├─ shebang-command@2.0.0
        ├─ shebang-regex@3.0.0
        ├─ slash@3.0.0
        ├─ string.prototype.matchall@4.0.7
        ├─ string.prototype.trimend@1.0.4
        ├─ string.prototype.trimstart@1.0.4
        ├─ strip-bom@3.0.0
        ├─ strip-json-comments@3.1.1
        ├─ supports-color@7.2.0
        ├─ supports-preserve-symlinks-flag@1.0.0
        ├─ text-table@0.2.0
        ├─ to-regex-range@5.0.1
        ├─ tsconfig-paths@3.14.0
        ├─ tslib@1.14.1
        ├─ tsutils@3.21.0
        ├─ type-check@0.4.0
        ├─ type-fest@0.20.2
        ├─ unbox-primitive@1.0.1
        ├─ uri-js@4.4.1
        ├─ v8-compile-cache@2.3.0
        ├─ which-boxed-primitive@1.0.2
        ├─ which@2.0.2
        └─ word-wrap@1.2.3
        
        We created the .eslintrc.json file for you and included your selected configuration.
        ready - ESLint has successfully been configured. Run next lint again to view warnings and errors.
        ✨  Done in 124.64s.
        ```
</details>        

3. 再びエラー

![スクリーンショット_2022-03-20_21.25.27.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/983bb22e-cf1e-19ff-6507-a8f47a2af8cd.png)

    
I’mの `‘`がエスケープ使わないといけないようで、今回は応急処置としてI amにしておく
ついでに警告で出ているpackage-lock.jsonも必要ないので削除。
    
Merge成功！やはりESlint入れたほうが型チェック入るのでよさげ

![スクリーンショット_2022-03-20_21.30.13.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1051129/1491e139-99fa-b820-a82c-ad04befa88fb.png)

---

### 最後に
短い記事でしたが最後まで見ていただきありがとうございました。

明日はJavaを少しかじっていたときのメモを投稿予定です。