LoginSignup
2
3

Vite / React / TypeScript で開発環境構築

Last updated at Posted at 2023-02-26

はじめに

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

ローカルサーバーが起動したことを確認できました。
image.png

設定ファイルのデフォルト値

各種設定ファイルのデフォルト値は以下の通りです。

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,
  },
});

3000 に変更できていることが確認できました。
image.png

ブラウザの自動起動

デフォルトでは、手動でブラウザを起動する必要があるので、自動で起動するように設定します。

vite.config.ts
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
  },
});

参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3