>Develop>React>React/TypeScriptの開発環境

Reactで遊んでみようと思い、Reactを勉強中。ということで、開発環境を作成するまでの流れをざっくりとまとめてみた。

Node.jsをインストール

Node.jsはオープンソースのWebアプリケーションのフレームワークで、Reactをベースに構築及び開発されている。TypeScriptのコンパイラやコマンドラインからコンパイルを実行できるCLIをインストールできる。

Download Node.js®

インストールできたら下記コマンドでNode.jsとパッケージマネージャーのnpmのバージョンが確認できる。

$ node --version
v22.18.0
$ npm --version
10.9.3

Powershellでnpmコマンドが実行できない場合

Powershellでnpmコマンドが実行したときに、ポリシーエラーで実行できなかった。そんなときはPowershellの実行ポリシーを変更することで、Powershellでもnpmコマンドが実行できるようになる。

PowerShell 実行ポリシー

$ winget search Microsoft.Powershell
Name               Id                           Version Source
---------------------------------------------------------------
PowerShell         Microsoft.PowerShell         7.5.2.0 winget
PowerShell Preview Microsoft.PowerShell.Preview 7.6.0.4 winget

下記コマンドで設定されている実行ポリシーを確認する。Restrictedだと、コマンドは許可されるが、スクリプトが許可されない。

$ Get-ExecutionPolicy
Restricted

下記のコマンドで実行ポリシーを設定する。RemoteSignedでスクリプトを実行できる。

Set-ExecutionPolicy RemoteSigned

再度、設定されている実行ポリシーを確認する。ちゃんとRemoteSignedに設定されている。これでPowershellでもnpmコマンドが実行できるようになるはず。

$ Get-ExecutionPolicy
RemoteSigned

TypeScriptの実行環境

TypeScriptのコンパイルなどをコマンドラインで実行するためのCLIパッケージをインストール。

$ npm install -g typescript

TypeScriptのコンパイルオプション

コンパイルに必要なオプションや対象のファイルの情報をなどを記述するJSONファイル。下記のコマンドでtsconfig.jsonが生成されるので、プロジェクトのルートに配置する。

$ tsc --init

tsconfig.jsonの例

{
  // Visit https://aka.ms/tsconfig to read more about this file
  "compilerOptions": {
    // File Layout
    // "rootDir": "./src",
    // "outDir": "./dist",

    // Environment Settings
    // See also https://aka.ms/tsconfig/module
    "module": "nodenext",
    "target": "esnext",
    "types": [],
    // For nodejs:
    // "lib": ["esnext"],
    // "types": ["node"],
    // and npm install -D @types/node

    // Other Outputs
    "sourceMap": true,
    "declaration": true,
    "declarationMap": true,

    // Stricter Typechecking Options
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,

    // Style Options
    // "noImplicitReturns": true,
    // "noImplicitOverride": true,
    // "noUnusedLocals": true,
    // "noUnusedParameters": true,
    // "noFallthroughCasesInSwitch": true,
    // "noPropertyAccessFromIndexSignature": true,

    // Recommended Options
    "strict": true,
    "jsx": "react-jsx",
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "noUncheckedSideEffectImports": true,
    "moduleDetection": "force",
    "skipLibCheck": true,
  }
}

nokmplicitAny

型が指定されておらず、TypeScriptが型推論できない場合、コンパイラのデフォルトではany(暗黙的なany)を使用する。any型はチェックが行われないため、なるべく利用を避ける必要がある。nokmplicitAnyオプションを使用することで、暗黙的なanyを使用した場合にコンパイルエラーを起こすように設定できる。

$ tsc --nokmplicitAny test.ts

strictNullChecks

通常は、変数にnullやundefinedであることを明示せずに利用することが可能だが、strictNullChecksオプションを使用することで、nullやundefinedを明示しなければコンパイルエラーを起こすことができる。

$ tsc --strictNullChecks test.ts

target

コンパイルを行う場合にどのバージョンのECMAScriptを出力するか指定することができる。例えば、古いバージョンをしているすることで、古いブラウザもサポートすることができる。

$ tsc --target es5 test.ts

ESLintの設定

静的解析ツールであるESLintにより、ソースコードの保守性を高めることができる。

ESLint関連のプラグインをインストールする。

  • prettier(フォーマッター)
  • eslint(リントツール)
  • typescript-eslint
  • @typescript-eslint/eslint-plugin
  • @typescript-eslint/parser
  • eslint-plugin-import
  • eslint-plugin-react-hooks
  • eslint-plugin-react
  • eslint-config-prettier
  • eslint-plugin-prettier
$ npm install --save-dev prettier eslint typescript-eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-import eslint-plugin-react-hooks eslint-plugin-react eslint-config-prettier eslint-plugin-prettier

プロジェクトディレクトリ直下にESLintの設定ファイル(.eslintrc.json)を作成する。下記は、設定例。

{
  "extends": [
    "next",
    "next/core-web-vitals",
    "eslint:recommended",
    "plugin:prettier/recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:import/recommended",
    "plugin:import/typescript"
  ],
  "rules": {
    "react/react-in-jsx-scope": "off",
    "import/order": [2, { "alphabetize": { "order": "asc" } }],
    "prettier/prettier": [
      "error",
      {
        "trailingComma": "all",
        "endOfLine": "lf",
        "semi": false,
        "singleQuote": true,
        "printWidth": 80,
        "tabWidth": 2
      }
    ]
  }
}

package.json の script を加える。

"scripts": {
  .
  .
  .
  "lint": "next lint --dir src",
  "format": "next lint --fix --dir src",
},

先程の script の設定で、下記のコマンドでlintコマンドが実行できる。

$ npm run lint

同様に、下記コマンドで自動フォーマとが実行できる。

$ npm run format

Reactの開発環境

下記コマンドでReactのプロジェクトを生成できる。

$ npx create-react-app [プロジェクト名]

TypeScriptの型が付けられたプロジェクトを生成する場合は–templateオプションで生成できる。

$ npx create-react-app [プロジェクト名] --template typescript

プロジェクトのルートディレクトリで、下記コマンドを実行するとローカルで開発サーバーを起動することができる。

$ npm run start
Compiled successfully!

You can now view src in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.56.1:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully
No issues found.

ローカルの開発サーバーにアクセスするとブラウザで下記のように表示される。これでひとまずReactが開発できるまでの環境が整った。

Reactに関する記事

Reactの挙動

最後にReactの挙動を簡単にまとめておく。Reactでは、コンポーネントをJSXを利用して書く。JavaScript XMLの略で、JavaScriptのコードの中に HTMLタグのような構文を書くことができる。JSXのコードはJavaScriptのビルドツールであるwebpackによってJavaScriptのコードに変換される。変換されたJavaScriptのコードをブラウザが読込み実行され描画される。JavaScriptのコードからブラウザの表示内容を書き換える際には、DOMにアクセスするが、Reactの描画エンジンの場合は、一旦仮想DOMを構築する。仮想DOMは、メモリ上に保存された疑似的なDOMツリーで、前回構築したDOMツリーと比較し、差分があるところのみを実際のDOMを更新する。差異の分だけを更新するため、高速に描画されるのが特徴。

Reactに関する記事

記事を読んでいただきありがとうございました。

Page Top