【React入門】初心者必見!React + TypeScriptで環境構築

2023年10月13日React,TypeScript

react_typescript

Reactとは

ReactとはJavaScriptを使ったフロントのフレームワークです。
仮想DOMへのレンダリングでの開発が行われるので、処理の高速です。
また、関数をコンポーネントを使って無駄のないプログラムを書いていく言語で人気のフレームワークの一つです。

ReactとTypeScriptでProjectを作成

npx create-react-app アプリ名 --template typescript
kami@kami dev % npx create-react-app react_ts_test --template typescript

Creating a new React app in /Users/kami/Desktop/work/dev/react_ts_test.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template-typescript...


added 1425 packages in 1m

229 packages are looking for funding
  run `npm fund` for details

Initialized a git repository.

Installing template dependencies using npm...

added 52 packages, and changed 2 packages in 11s

238 packages are looking for funding
  run `npm fund` for details

We detected TypeScript in your project (src/App.test.tsx) and created a tsconfig.json file for you.

Your tsconfig.json has been populated with default values.

Removing template package using npm...


removed 1 package, and audited 1477 packages in 1s

238 packages are looking for funding
  run `npm fund` for details

6 high severity vulnerabilities

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

Created git commit.

Success! Created react_ts_test at /Users/kami/Desktop/work/dev/react_ts_test
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react_ts_test
  npm start

Happy hacking!

スポンサードサーチ

プロジェクト構造

App名
┣ node_modules
┣ public
┣ src
.gitignore
package-lock.json
package.json
README.md
tsconfig.json

JavaScriptとのReactとの違いは「tsconfig.json」ファイルが存在するのと、構文に型が記述されていたりします。

icon

以下のファイルは不要なので削除しても構いません

  • setupTests.ts
  • reportWebVitals.ts
  • logo.svg

tsconfig.json

「tsconfig.json」ファイルはTypeScriptの設定ファイルが記述されています。

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

スポンサードサーチ

public/index.html

index.htmlでポイントは「body」タグ内にある「id="root"」です。
このidにReactファイルを読み込ませるようにプログラムを書いていきます。

icon

ここはJavaScriptもTypeScriptも一緒ですね

src/App.tsx

「src/App.tsx」ではApp関数内にHTMLの記述をしています。
tsxの拡張子はTypeScriptとHMLの記述をすることができます。

classの書き方

<div className="App">

imgの書き方

        <img src={logo} className="App-logo" alt="logo" />

aタグの書き方

        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

スポンサードサーチ

src/index.tsx

「src/index.tsx」は、
index.tsxでは、React要素をルートをDOMノードにレンダーするには、まず ReactDOM.createRoot() に DOM 要素を渡し、root.render() に React 要素を渡します。

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Reactでローカルサーバーを起動

カレントディレクトリをApp名に変更して「npm start」コマンドを叩きます

cd App名
npm start

※npmのscriptsコマンドはpackage.jsonのscriptsに記述されています。

http://localhost:3000/

上記、ポート番号でReact開発のローカルサーバーが起動を確認できます。

React,TypeScript環境構築

Posted by kami