はじめに
Viteを利用したプロジェクトの作成・設定手順のメモです。
開発環境は以下の通りです。
- Windows11
- VSCode
- Vite 4.1.0
- React 18.0.27
- TypeScript 4.9.3
プロジェクト作成
以下のコマンドでプロジェクトを作成します。
yarn create vite react-tests --template react-ts
今回は React / TypeScript のテンプレートを利用しましたが、それ以外のテンプレートも数多く用意されています。
https://github.com/vitejs/vite/tree/main/packages/create-vite
次にプロジェクトディレクトに移動した後、以下のコマンドを実行し、ローカルサーバーを起動します。
yarn
yarn dev
ローカルサーバーが起動したことを確認できました。
設定ファイルのデフォルト値
各種設定ファイルのデフォルト値は以下の通りです。
package.json
{
"name": "react-tests",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^3.1.0",
"typescript": "^4.9.3",
"vite": "^4.1.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"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()],
})
Viteの設定
Viteの各種設定を行っていきます。
デフォルトで用意されている defineConfig
が自動補完してくれるので便利です。
ポートの変更
デフォルト値は 5173
なので、3000
に変更します。
vite.config.ts
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
},
});
ブラウザの自動起動
デフォルトでは、手動でブラウザを起動する必要があるので、自動で起動するように設定します。
vite.config.ts
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
open: true,
},
});