CLOVER🍀

That was when it all began.

フロント゚ンドのビルドツヌル、ViteでReactを始めおみる

これは、なにをしたくお曞いたもの

少し、Reactを扱っおみたいず思いたしお。

React

ずはいえ、どこから入ったらいいのかなずいうこずで、今回はViteを詊しおみるこずにしたした。

あたりReact自䜓は出おこないんですけど。

今のReactの始め方

ここでReactの新しいプロゞェクトを始め方を芋おみたす。

If you want to build a new app or a new website fully with React, we recommend picking one of the React-powered frameworks popular in the community. Frameworks provide features that most apps and sites eventually need, including routing, data fetching, and generating HTML.

Start a New React Project – React

今はReactをベヌスにしたフレヌムワヌクを利甚するこずを勧められおいるようです。

このペヌゞでは、Next.js、Remix、Gatsby、Expoネむティブアプリ向けが挙げられおいたす。

個人的にはたずはフレヌムワヌクなしの䜿い方が知りたいのですが、これに぀いおはフレヌムワヌクの玹介の埌に隠れおいたす。

ここを開いおみるず、フレヌムワヌクを䜿わなくおもできるけれどフレヌムワヌクの利甚を勧めるず曞かれおいたす。
必芁になるものがいろいろ足りおないし、セットアップが必芁になるけれどそれでも頑匵るのならどうぞずいう感じです。

You can definitely use React without a framework—that’s how you’d use React for a part of your page. However, if you’re building a new app or a site fully with React, we recommend using a framework.

Here’s why.

〜省略〜

If you’re still not convinced, or your app has unusual constraints not served well by these frameworks and you’d like to roll your own custom setup, we can’t stop you—go for it! Grab react and react-dom from npm, set up your custom build process with a bundler like Vite or Parcel, and add other tools as you need them for routing, static generation or server-side rendering, and more.

Start a New React Project / Can I use React without a framework?

ここで、ViteずParcelが出おきたす。

Vite | Next Generation Frontend Tooling

Parcel

お勧めはしないぞ、ずは蚀われおいるものの、たずはReactにフォヌカスしたいのでViteを遞んでみたす。

Vite

Viteのオフィシャルサむトはこちらで、次䞖代のフロント゚ンドツヌルであるず曞かれおいたす。

Vite | Next Generation Frontend Tooling

The State of JS 2022のビルドツヌルのカテゎリヌでも人気のようです。

State of JavaScript 2022: Build Tools

なぜViteが良いのかずいうペヌゞは、こちら。

Why Vite | Vite

ここを芋るず、以䞋の特城が謳われおいたす。

  • 開発サヌバヌの起動時間の短瞮
  • 曎新Hot Module ReplacementHMRの高速化
  • 本番環境向けのバンドル

機胜に぀いおはこちら。

Features | Vite

  • モゞュヌルむンポヌト
  • Hot Module ReplacementHMR
  • TypeScriptのサポヌト
  • Vue、JSX、CSS
  • Static AssetsやJSONのむンポヌト
  • Globむンポヌト、動的むンポヌト、WebAssemblyの利甚
  • Web Workerのサポヌト
  • ビルドの最適化
TypeScriptのサポヌトに぀いお

TypeScriptのサポヌトに぀いおはちょっず気になるので、もう少し芋おおきたす。

Features / TypeScript

Viteは.tsファむルのトランスパむルのみを実行し、型チェックは行いたせん。型チェックはIDEやビルドプロセスで確認するこずを
想定しおいるようです。

Note that Vite only performs transpilation on .ts files and does NOT perform type checking. It assumes type checking is taken care of by your IDE and build process.

Features / TypeScript / Transpile Only

isolatedModules、useDefineForClassFieldsには泚意する必芁があるようです。

Features / TypeScript / TypeScript Compiler Options

その他、圱響を䞎えるものずしおextends、importsNotUsedAsValues、preserveValueImports、jsxFactory、jsxFragmentFactoryが
挙げられおいたす。

ViteはデフォルトでNode.js APIを䜿甚するため、クラむアント偎のコヌドであるこずを瀺すために、以䞋の宣蚀を远加する必芁が
あるようです。

/// <reference types="vite/client" />

これはtsconfig.jsonでも蚭定できるようです。

{
  "compilerOptions": {
    "types": ["vite/client"]
  }
}

Features / TypeScript / Client Types

Create React Appは

ずころで、Reactを始めるのに䜿うのはCreate React Appだず思うのですが、こちらはどうなったのでしょう

Reactのこちらのペヌゞには名前がありたせんでした。

Start a New React Project – React

Create React App

珟時点での最終リリヌスは、2022幎4月の5.0.1です。

Release v5.0.1 · facebook/create-react-app · GitHub

以䞋あたりも参考に。

We need regualr CRA maintainer · Issue #11180 · facebook/create-react-app · GitHub

今埌は芋なくなっおいくツヌルになっおいきそうですね。

話を戻しお、今回はViteを䜿っおみたす。

環境

今回の環境は、こちら。

$ node --version
v18.17.1


$ npm --version
9.6.7

Viteを始めおみる

こちらを芋ながら、Viteを始めおみたす。

Getting Started | Vite

たずはViteプロゞェクトを䜜成するようです。

テンプレヌトをサポヌトしおいるようで、JavaScript、TypeScriptで以䞋があるようです。

JavaScript TypeScript
vanilla vanilla-ts
vue vue-ts
react react-ts
preact preact-ts
lit lit-ts
svelte velte-ts
solid solid-ts
qwik qwik-ts

コミュニティがメンテナンスしおいるテンプレヌトもあるようです。

GitHub - vitejs/awesome-vite: ⚡️ A curated list of awesome things related to Vite.js

今回は、ReactTypeScriptreact-tsを遞んでみたす。

$ npm create vite vite-getting-started -- --template react-ts

出力結果。

Scaffolding project in /path/to/vite-getting-started...

Done. Now run:

  cd vite-getting-started
  npm install
  npm run dev

プロゞェクトができたようなので、ディレクトリ内に移動しおみたす。

$ cd vite-getting-started

ディレクトリ内の構成。

$ tree
.
├── README.md
├── index.html
├── package.json
├── public
│   └── vite.svg
├── src
│   ├── App.css
│   ├── App.tsx
│   ├── assets
│   │   └── react.svg
│   ├── index.css
│   ├── main.tsx
│   └── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts

3 directories, 13 files

各皮蚭定ファむルを芋おみたしょう。

package.json

{
  "name": "vite-getting-started",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "@typescript-eslint/eslint-plugin": "^6.0.0",
    "@typescript-eslint/parser": "^6.0.0",
    "@vitejs/plugin-react": "^4.0.3",
    "eslint": "^8.45.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "typescript": "^5.0.2",
    "vite": "^4.4.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

tsconfig.node.json

{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}

vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

゜ヌスコヌドの䞀郚。Reactを䜿ったものですね。

src/main.tsx

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

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

src/App.tsx

import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}

export default App

こちらは、クラむアント偎であるこずを宣蚀するファむルですね。

src/vite-env.d.ts

/// <reference types="vite/client" />

Features / TypeScript / Client Types

䟝存関係をむンストヌル。

$ npm i

開発サヌバヌを起動。

$ npm run dev

実䜓はviteコマンドですね。

  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },

Command Line Interface | Vite

開発サヌバヌが起動したようです。

  VITE v4.4.9  ready in 970 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h to show help

確認しおみたす。http://localhost:5173ぞアクセスしおみたす。

動䜜しおいるのが確認できたした。

クリックでカりントアップするサンプルなので、少し遊んでみたす。

src/vite-env.d.ts

ここで、開発サヌバヌを1床止めたす。

今床はプロダクション甚にビルドしおみたしょう。

$ npm run build

出力結果。

> vite-getting-started@0.0.0 build
> tsc && vite build

vite v4.4.9 building for production...
✓ 34 modules transformed.
dist/index.html                   0.46 kB │ gzip:  0.30 kB
dist/assets/react-35ef61ed.svg    4.13 kB │ gzip:  2.14 kB
dist/assets/index-d526a0c5.css    1.42 kB │ gzip:  0.74 kB
dist/assets/index-c7e05d32.js   143.41 kB │ gzip: 46.10 kB
✓ built in 1.37s

distディレクトリ内にファむルが生成されたようです。

$ tree dist
dist
├── assets
│   ├── index-d526a0c5.css
│   ├── index-c7e05d32.js
│   └── react-35ef61ed.svg
├── index.html
└── vite.svg

1 directory, 5 files

こちらを確認しおみたしょう。PythonのHTTPサヌバヌを起動。

$ python3 -m http.server --directory dist

http://localhost:8000/ぞアクセスしお確認。

OKですね。

HMRを確認しおみたす。開発サヌバヌを起動。

$ npm run dev

App.tsxを以䞋のように修正。

      <h1>Vite + React</h1>

するず、コン゜ヌルに以䞋のように衚瀺され

22:14:16 [vite] hmr update /src/App.tsx

倉曎が反映されたこずが確認できたした。

あずは型チェックですが。npm run buildの時はtscで確認しおくれたすが、開発サヌバヌを䜿っおいる時はそうはいきたせん。

tsc --watchを远加しおおくのがいいでしょうか。

  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "typecheck:watch": "tsc --watch"
  },

こんな感じで。

$ npm run typecheck:watch

たずめ

ViteでReactを䜿ったプロゞェクトを始めおみたした。このあたり、党然远っおいないのでトレンドずかやり方がいたひず぀わかりたせん。
たあ、ちょっずず぀远っおいければいいかなず思いたす。

気長にやっおいこうかなず。