3
11

More than 3 years have passed since last update.

Next.jsではじめるTypeScript

Last updated at Posted at 2020-01-08

今回は、Next.jsを利用して、TypeScriptに挑戦しようという記事です

テーマ

  • TypeScriptの第一歩をNext.jsで整えよう

対象読者

  • JavaScriptわかる
  • Reactそこそこわかる
  • Next.js触ったことある
  • TypeScript初心者

ぐらいを想定です。

前提条件

  • node.jsインストール済み

プロジェクト作成

ディレクトリつくる

$ mkdir awesome-pjt && cd awesome-pjt

プロジェクト作成

$ npm init -y

ライブラリインストール

$ npm install --save next react react-dom

Next.jsのコマンド追加

$ vim package.json
package.json
{
  ...
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  ...
}

Next.jsのエントリーファイルを作成

$ mkdir pages && touch pages/index.js

ファイル編集(JavaScript)

$ vim pages/index.jsx
index.jsx
import React from 'react';

const Index = () => {
  return (
    <div>Hello, World</div>
  );
};

export default Index;

ローカルサーバ起動

$ npm run dev

http://localhost:3000にアクセスすると、Hello, Worldが表示されます。

ここまでが Next.jsJavaScript で利用した場合です。
続いて、TypeScriptを利用した場合にしてみましょう。

ファイル名変更(TypeScript)

$ mv pages/index.jsx pages/index.tsx

型ファイルライブラリをインストール

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

configファイルを作成

$ touch tsconfig.json
tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "allowSyntheticDefaultImports": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

エントリーファイルを更新

$ vim pages/index.tsx

返すコンポーネントに型情報を追加

index.jsx
import React from 'react';

const Index = (): JSX.Element => {
  return (
    <div>Hello, World</div>
  );
};

export default Index;

ローカルサーバ再起動し、http://localhost:3000で、Hello, Worldが表示されれば、成功です。


(補足)自動生成定義ファイル

next-env.d.ts が自動生成されますが、TypeScriptがコンパイル時に生成しているファイルです。
Next.jsで、以下のように書かれています。

Note: Next.js will create a file named next-env.d.ts in the root of your project. This file ensures Next.js' types are picked up by the TypeScript compiler.

You cannot remove this file, however, you can edit it (but don't need to).

3
11
0

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
3
11