Viteを使ってReactの環境を作成する流れをメモ。
設定方法
プロジェクトを作成するディレクトリに移動して、下記コマンドを実行します。
1 | npm create vite@latest |
プロジェクト名(作成するフォルダ名)を入力します。
1 | ? Project name: |
使用するライブラリの一覧でReactを選択します。
1 2 3 4 5 6 7 8 9 10 | ? Select a framework: » - Use arrow-keys. Return to submit. > Vanilla Vue React Preact Lit Svelte Solid Qwik Others |
TypeScriptかJavaScriptを選択します。
1 2 3 4 5 6 | ? Select a variant: » - Use arrow-keys. Return to submit. > TypeScript TypeScript + SWC JavaScript JavaScript + SWC Remix |
これでプロジェクト作成が完了したので、プロジェクトのディレクトリに移動してインストールを行います。
1 | npm install |
これで環境の準備ができました。
下記コマンドで開発サーバを起動できます。
1 | npm run dev |
ディレクトリ構成
ディレクトリ構成は以下のようになっています。
- public
- vite.svg
- src
- assets
- react.svg
- App.css
- App.jsx
- index.css
- main.jsx
- assets
- .eslintrc.cjs
- .gitignore
- index.html
- package.json
- package-lock.json
- README.md
- vite.config.js
エンドポイントのindex.htmlは以下のようになっています。
1 2 3 4 5 6 7 8 9 10 11 12 13 | <! doctype html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < link rel = "icon" type = "image/svg+xml" href = "/vite.svg" /> < meta name = "viewport" content = "width=device-width, initial-scale=1.0" /> < title >Vite + React</ title > </ head > < body > < div id = "root" ></ div > < script type = "module" src = "/src/main.jsx" ></ script > </ body > </ html > |
index.htmlで読み込まれているsrc/main.jsxの中身は以下になります。
1 2 3 4 5 6 7 8 9 10 | import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.jsx' import './index.css' ReactDOM.createRoot(document.getElementById( 'root' )).render( <React.StrictMode> <App /> </React.StrictMode>, ) |
src/App.jsxの中身は以下になります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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> <img src={viteLogo} className= "logo" alt= "Vite logo" /> </a> <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.jsx</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 |
ビルド
ビルドは下記コマンドを実行します。
1 | npm run build |
distフォルダが作成され、その中にファイルが出力されます。
Vite + Reactのデモページ
コメントが承認されるまで時間がかかります。