viteでReact×TypeScript環境を作る
色々bundleツールがありますが、
esbuildベースのviteがビルドが早く、かつwebpackのような細かい設定までできるため、
最近はよく使っています。
また開発ビルド時にはソースコード変更時に自動的にブラウザ反映してくれるHMRが動作するため、
非常に快適に開発できます。
身も蓋もないやり方だと、以下のviteコマンドのインタラクションを選ぶだけでテンプレート作ってくれます。
$ npm create vite@latest
// yarnの場合は
$ yarn create vite@latest
frameworkはReactを選択します
SWCを選択したほうがより高速にビルドしてくれます。
それだけだと芸がないので軽く解説します。
サンプル
github
サンプルのフォルダ構成は簡易のため、以下のように変更しています。
.
├── README.md
├── package.json
├── src
│ ├── App.tsx
│ ├── index.html
│ ├── main.tsx
│ └── vite-env.d.ts
├── tsconfig.json
├── vite.config.ts
└── yarn.lock
package.jsonは以下のようになっています。
npm dev
で開発ビルド、npm build
で本番ビルドできます。
{
"name": "vite-react",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^20.6.0",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react-swc": "^3.3.2",
"typescript": "^5.0.2",
"vite": "^4.4.5"
}
}
viteのbuild設定はvite.config.tsに記述します。
@vitejs/plugin-react-swc
のプラグイン設定が必要です。
buildプロパティに細かい設定を書いていきます。
サンプルではproduction build向けの設定を書いています。
import { resolve } from 'path';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
// https://vitejs.dev/config/
export default defineConfig({
root: 'src',
plugins: [react()],
build: {
// distフォルダに出力
outDir: resolve(__dirname, 'dist'),
// 存在しないときはフォルダを作成する
emptyOutDir: true,
rollupOptions: {
// entry pointがあるindex.htmlのパス
input: {
'': resolve(__dirname, 'src/index.html'),
},
// bundle.jsを差し替えする
output: {
entryFileNames: `assets/[name]/bundle.js`,
},
},
},
});
src/index.htmlにReact Applicationを埋め込むhtmlが記述してあります。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>タイトル</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="module" src="/main.tsx"></script>
</head>
<body>
<div id="root" />
</body>
</html>
src/main.tsxはReactの初期化処理を書いています。
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
src/vite-env.d.tsは環境変数の型を定義するためのものです。
viteは内包しているdotenvライブラリで環境変数を定義することができるため、
環境変数の型定義をこのファイルに追記することで環境変数の型を参照先で使うことができます。
/// <reference types="vite/client" />
// 以下にReactで参照する環境変数の型定義を書く
ESLint, Prettier導入
文法チェックとコードフォーマッターを導入します。
この辺はやりかたは色々あるし、
どのパッケージ入れるかやeslintやprettierルールの好みもあるので
参考程度に
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"prettier": "^3.0.0",
}
eslintで文法チェックルールは.eslintrc.cjsに定義します。
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['react-refresh', '@typescript-eslint/eslint-plugin'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'plugin:prettier/recommended',
],
env: {
node: true,
jest: true,
browser: true,
es2020: true,
},
ignorePatterns: ['dist', '.eslintrc.cjs'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
.prettierrcに文法フォーマットのルールを作成します。
{
"tabWidth": 2,
"singleQuote": true,
"semi": false,
"trailingComma": "all"
}
本番ビルドは以下のコマンドで生成されたdistフォルダを
そのままホスティングすれば表示できます。
$ npm build
もしくはyarnの場合は
$ yarn build
CSSライブラリ導入
CSSをインラインで直接書いたり、vite自体もCSSモジュールをサポートしていますが、
- cssをモジュール化したい
- global style書きたい
- media query書きたい
- Themeで一括にアプリ全体のCSSを適用したい
みたいなことがよくあるので
vanilla-extractが軽量ミニマムでかつ上記の機能備えていてtype safeで
最小の開発時は便利なので入れます。
https://vanilla-extract.style/
導入自体は簡単です。
package.jsonにパッケージを追加してインストール。
"dependencies": {
"@vanilla-extract/css": "^1.13.0",
}
"devDependencies": {
"@vanilla-extract/vite-plugin": "^3.9.0",
}
vite.config.tsにプラグインを追加
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), vanillaExtractPlugin()],