😺
【メモ】TypeScriptプロジェクト初期セットアップ(Vite版)
目標
- Vitaを利用してHTML+TypeScriptのプロジェクトを作成
- HTML+TypeScriptのコンテンツをViteサーバーで提供。
- gtsを利用してGoogle TypeScript Style Guideに従うようにESLintを設定。
- VSCodeで編集時にlinter、保存時にformatterが効くようにする。
前提
- 2025/6の時点での情報に従う。
- nodejsの環境はセットアップ済み。
- VSCodeはセットアップ済み。
セットアップ
webpackインストール
npm init vite@latest . -- --template vanilla-ts
ESLintセットアップ
gtsをインストールすると、それに依存するESLintがインストールされる。
npm install --save-dev gts
npx gts init
? Overwrite
にNo
で答えて以下の修正を入れる。
diff --git a/tsconfig.json b/tsconfig.json
index a22caba..9f6a0fd 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,4 +1,5 @@
{
+ "extends": "./node_modules/gts/tsconfig-google.json",
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
VSCodeセットアップ
.vscode/settings.json
を作成(すでに存在する場合は編集)
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.fixAll.eslint": "explicit"
},
"eslint.validate": [
"typescript"
],
"eslint.format.enable": true
}
VSCodeを起動し、ESLintをExtentionをインストール。
.prettierrc.js
のエラー
下記のようなESLintエラーが出る。
[Error - 16:38:52] An unexpected error occurred:
[Error - 16:38:52] ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '.../package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file://.../.prettierrc.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:263:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:540:24)
at async loadJs (file://.../node_modules/prettier/index.mjs:16053:18)
at async loadConfig (file://.../node_modules/prettier/index.mjs:17570:16)
at async loadPrettierConfig2 (file://.../node_modules/prettier/index.mjs:17639:18)
at async Promise.all (index 0)
at async Module.resolveConfig (file://.../node_modules/prettier/index.mjs:17645:38)
at async .../node_modules/eslint-plugin-prettier/worker.js:40:9
エラーメッセージにかかれている通り名前を変更する。
mv .prettierrc.js .prettierrc.cjs
linter/formatterの動作確認
src/index.ts
を編集して意図的にワーニングが発生するような修正を行う。
例えば、文末のセミコロンを削除する。
修正を行った時点で、赤い下線で問題が指摘されていることを確認する。
保存した時点で、自動修正可能な問題が修正されることを確認する。(セミコロンであれば補完される)
もし期待通りならなければ、コマンドパレット(Shift
+Ctrl
+P
)を開いてESLint: Restert ESLint Server
を試す。それでもダメならOUTPUT
を開いてESLint
を選択し、問題を調査して対処する。
Viteサーバーの確認
実行:
npx vite
出力:
Port 5173 is in use, trying another one...
VITE v6.3.5 ready in 145 ms
➜ Local: http://localhost:5174/
➜ Network: use --host to expose
➜ press h + enter to show help
ブラウザで表示されているURLにアクセスして確認。
Discussion