0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

既存Next.jsプロジェクトにTypeScriptを導入する方法

Last updated at Posted at 2024-08-07

アジェンダ

既存プロジェクトにTypeScriptを導入する方法を簡単にまとめます。今回は、Next.js、 JavaScriptの既存プロジェクトがあることを前提にいたします。

手順

1. TypeScriptと必要なパッケージのインストール

次に、TypeScriptとその型定義ファイルをインストールします。

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

2. TypeScriptファイルの作成

tsconfig.jsonファイルをプロジェクトのルートディレクトリに作成します。Next.jsはこのファイルが存在することを検出すると、自動的にTypeScriptサポートを有効にします。

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",
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

また、プロジェクトのルートディレクトリにnext-env.d.tsファイルを作成します。

/// <reference types="next" />
/// <reference types="next/types/global" />

3. TypeScriptにファイルを変換

既存のJavaScriptファイル(.js)をTypeScriptファイル(.ts または .tsx)に変換します。例えば、pages/index.jspages/index.tsxにリネームします。

4. TypeScript設定の微調整

必要に応じてtsconfig.jsonファイルの設定を調整します。strictモードを無効にするなど、プロジェクトのニーズに応じて変更できます。

5. プロジェクトの実行

TypeScriptの設定が正しく行われたことを確認するために、プロジェクトを実行します。

npm run dev

エラーが発生しないことを確認してください。

まとめ

Next.jsプロジェクトにTypeScriptを導入するには、TypeScriptと型定義ファイルをインストールし、tsconfig.jsonファイルとnext-env.d.tsファイルを設定するだけです。これにより、TypeScriptを使用した型安全な開発が可能になります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?