1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Tanstack Routerで`npx create-tsrouter-app@latest my-app`をした際に生成されるvite.config.tsのエラー修正方法

Posted at

はじめに

tanstack Routerで新しくプロジェクトを生成した際にテンプレートコマンドを利用してプロジェクトを作成した際におきたエラーについて解決方法をまとめます。

問題

ファイルベースのルーティングなどを行ってくれるTanstack routerですが、以下のコマンドを利用してプロジェクトに必要なコードなどのテンプレートを作成した状態で始めることが出来ます。

しかし、そのままだと、生成されたコード内でviteの設定を行っているvite.config.tsファイルでエラーになります

tanstack routerのテンプレート作成コマンド
// 余談:shadcnUI等を使用する際、add-onsのあとに指定することで勝手にインストールしてくれます
npx create-tsrouter-app@latest my-app --template file-router --tailwind --add-ons shadcn

エラーが起きているコードを貼ってしまうとエラーが起きている箇所が分かりづらいため、画像を貼ります。
image.png

ざっくりとしたエラーの内容ですが、順に説明します。

1. TanstackRouterViteの部分

これは、度重なるTanstack routerのアップデートにより、TanstackRouterViteというpluginsが非推奨になったためエラーが起きています。なので修正としては現在使用されているpluginsであるtanstackRouterにすることで解決出来ます。

2. node:pathの部分

これは、node:pathモジュールの型宣言が見つからないことにより起きています。解決策として一番シンプルなのが、型宣言をtsconfig.tsに追加することです。@types/nodeをインストールしましょう。

ステップ1 型をインストール

npm i --D @types/node

ステップ2 tsconfig.tsのtypesに@types/nodeを追加

{
  "include": ["**/*.ts", "**/*.tsx"],
  "compilerOptions": {
    "target": "ES2022",
    "jsx": "react-jsx",
    "module": "ESNext",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "types": ["vite/client", "@types/node"], ここ
    
}

実はもう一つ解決方法があり、私としてはこちらの方法を推奨します。
vite.config.tsでnote:pathを利用してやりたいことらパスエイリアスの設定です。

viteではvite-tesconfig-pathsを利用することで簡単にパスエイリアスを設定できます。

ステップ1

npm i -D vite-tsconfig-paths

ステップ2 tsconfig.josnの設定

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

3. defineConfig内のtestプロパティのエラー

このエラーは、viteからインポートされているdefineConfigではtestプロパティが設定出来ないため起きています。

じゃあどうするのか、、

vitest/configからエクスポートされているdefineConfigを利用することで解決できます。

import { defineConfig } from "vitest/config"

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
  },
})

修正された全体のコード

import { defineConfig } from "vitest/config"
import viteReact from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
import tsconfigPaths from "vite-tsconfig-paths"

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [tanstackRouter({ autoCodeSplitting: true }), viteReact(), tsconfigPaths()],
  test: {
    globals: true,
    environment: 'jsdom',
  },
})

おわりに

Tanstack Routerで新しくプロジェクトを作成した際に手助けとなれば幸いです。

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてくださ!
▼▼▼

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?