LoginSignup
0
1

Viteでvanilla-ts開発環境

Last updated at Posted at 2024-05-04

Viteのことはじめとして単純なTypeScript開発環境を構築してみました。

ライブラリの検証などに使用したり、しょぼアプリ開発をしたいときに簡単な開発環境が欲しく、作ってみました。

公式ガイドはこちら。迷ったときは公式ガイド!

最初の環境構築

正直コレがほぼすべて…

# current directoryに作ります
yarn create vite@latest ./ --template vanilla-ts
# package.jsonの内容をインストール
yarn

起動するとこんな画面が出ます。

# 起動
yarn dev
# o でブラウザで開きます。
# 起動時にteminalに表示されるlocalhostのアドレスにアクセスしてももちろんOK!
o

image.png

とりあえずこれだけでViteの開発環境の9割は完了。
表示されてるカウンターのボタンを押すとカウントが上がります。

ちなみに h でその他どういうコマンドがあるか表示されます

試しに変更

ではカウンターを上げた後HTMLを変更してみます。

index.html
<!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 + TS</title>
  </head>
  <body>
    <div id="app"></div>
+   <div id="hoge">ほげ</div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

image.png

HMRではなくhot reloadされますね。カウンターを見る限り。
にしても速い!

CSS modules

ついでにCSS modulesもデフォで効くとのことなので、検証。
先ほどのhogeの背景色を赤にしてみます。

このcssファイルを追加。

test.module.css
.hoge {
    background-color: red;
}
main.ts
import './style.css'
+ import mystyles from './test.module.css';
import typescriptLogo from './typescript.svg'
import viteLogo from '/vite.svg'
import { setupCounter } from './counter.ts'

// ...中略

+ // css modulesでスタイル適用
+ document.getElementById("hoge")!.classList.add(mystyles.hoge)

image.png

ばっちりですね。

番外: wslでもhot reload

実はwindowsの場合、powershellやcommand promptなどwindowsのterminalでは良いんですが、wslではhot reloadが効きません。

しかしwslでも使いたい、チーム開発で他の人はどのターミナルを使用するかわからないなどの場合でも対応する方法はあります。

vite.config.jsというviteの設定ファイルを追加し、以下の記述をします。

vite.config.js
import { defineConfig } from "vite";

export default defineConfig({
  server: {
    watch: {
      usePolling: true,
    },
  },
});

これでwslを使用してyarn devで起動してもhot reloadが効きます!

終わりに

ほんとに爆速でびっくりしました。

CRAでReactアプリをよく作ってたんですが、置き換えていきたい…。

0
1
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
0
1