JavaScript/TypeScriptメモ

Next.jsでTypeScriptを導入する手順

Next.jsでTypeScriptを導入する手順

Next.jsでTypeScript環境を導入する手順をまとめます。

1. Next.js インストール

Tutorialの手順(に近い手順)でインストールをします。

※今回は、exampleは指定していません。

npx create-next-app nextjs-blog --use-npm

参考:Create a Next.js App

2. TypeScriptの(自動)設定

TypeScript関連のnpmパッケージをインストールし、空のtsconfig.jsonを作成します

あとは、開発用サーバを立ち上げましょう。

npm install --save-dev typescript @types/react @types/node
touch tsconfig.json
npm run dev

これで、tsconfig.jsonが自動的に編集され、next-env.d.tsが自動で作成されます。

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"
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}
next-env.d.ts(自動生成)
/// <reference types="next" />
/// <reference types="next/types/global" />

3. tsconfig.jsonの書き換え

自動生成されたtsconfig.jsonでは、"strict": falseと設定されているため、"strict": trueに修正しておきましょう。

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

これで、TypeScriptが使えるようになります。

あとは、好みに合わせて修正をしていってください。

自動生成されたjsファイルをts、tsxファイルに修正する

自動生成された表示用のjsファイルをts、tsxファイルに修正しておきましょう。

pages/index.js → index.tsx

「pages」以下の表示用コンポーネントについては、constで宣言した変数に、React.FC型を付けておけば大丈夫なようです。

そこで、元々のソースコードを修正していきます。

元々のHomefunctionで定義されています。そこで、constを使った定義に変えて、変数Homeに、関数の型(React.FC)を付けます。

また、const宣言だとdefault exportができないので、別途default exportを追加します。

pages/index.tsx
import Head from 'next/head';
import styles from '../styles/Home.module.css';

const Home: React.FC = () => {  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      //...
      //(略)
      //...

      <footer className={styles.footer}>

        //...
        //(略)
        //...

      </footer>
    </div>
  );
};

export default Home;

pages/_app.js → _app.tsx

これも、先ほどと同じように、コンポーネントにReact.FC型を付けます。

なお、「_app.tsx」で作成するコンポーネントは引数を受け取るので、React.FCの型変数に「引数の型」を指定する必要があります。

そこで、型定義をimportして、引数に型を付けます。

_app.tsx
import { AppProps } from 'next/app';import '../styles/globals.css';

const MyApp: React.FC<AppProps> = ({ Component, pageProps }) => {  return <Component {...pageProps} />;
};

export default MyApp;

pages/api/hello.js → hello.tsx

型定義をimportして、引数に型を付けます。

pages/api/hello.tsx
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { NextApiRequest, NextApiResponse } from 'next';
export default (req: NextApiRequest, res: NextApiResponse): void => {  res.statusCode = 200;
  res.json({ name: 'John Doe' });
};

まとめ

「tsconfig.json」の"strict": trueを、忘れると後が大変そうなので、気を付けましょう。