2
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?

plugin:vite:import-analysis Failed to resolve importエラーが出る。

2
Posted at

はじめに

Vite + React + TypeScript で環境を構築後に、ChakraUiのセットアップしている中で問題が起きました。

問題

ChakraUiのセットアップの手順通りに行いましたが、画面で以下のエラーが出ました。

[plugin:vite:import-analysis] Failed to resolve import "@/components/ui/provider" from "src/main.tsx". Does the file exist?
/Applications/github/type-class/src/main.tsx:3:25
1  |  import { StrictMode } from "react";
2  |  import { createRoot } from "react-dom/client";
3  |  import { Provider } from "@/components/ui/provider";
   |                            ^
4  |  import "./index.css";
5  |  import App from "./App.tsx";
    at TransformPluginContext._formatLog (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:30375:39)
    at TransformPluginContext.error (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:30372:14)
    at normalizeUrl (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:27654:18)
    at async file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:27717:30
    at async Promise.all (index 2)
    at async TransformPluginContext.transform (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:27685:4)
    at async EnvironmentPluginContainer.transform (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:30164:14)
    at async loadAndTransform (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:24512:26)
    at async viteTransformMiddleware (file:///Applications/github/type-class/node_modules/vite/dist/node/chunks/node.js:24306:20)

原因

tsconfig.jsonpaths を設定していても、Vite はデフォルトで tsconfig の paths を読まないため、このエラーが発生していたようです。

// tsconfig.app.json(設定しているのに解決されない)
"paths": {
  "@/*": ["./src/*"]
}

解決方法

vite-tsconfig-paths プラグインを使い、tsconfig の paths を Vite に読み込ませることで解決しました。

1. インストール

npm install -D vite-tsconfig-paths

2. vite.config.ts に追加

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [react(), tsconfigPaths()],
})

これだけで @/ エイリアスが Vite と TypeScript(VS Code)の両方で正しく解決されます。

注意: TypeScript 4.1 以降、paths の使用に baseUrl は不要です。baseUrl は TypeScript 7.0 で廃止予定のため、設定しないようにしましょう。

おわりに

環境構築における「設定したはずなのに動かない」という問題は、ViteとTypeScriptの役割分担を理解する良いきっかけになりました。同じエラーに直面した方の参考になれば幸いです。

参考

2
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
2
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?