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

参照先がindex.tsxではなくindex.tsになってしまう

Posted at

TypeScriptと使ってプロジェクトにおいてUIコンポーネントを作成して、いざ活用して別のコンポーネントを作成しようと際に、index.tsxではなくindex.tsを参照してしまう問題に直面しました。その当時のディレクトリ設計やtsconfig.jsonと合わせて説明しようと思います。

ディレクトリ設計

ざっくりですが、以下のようなディレクトリ設計を組んでました。

apps/
├── routes/
│   └── _index.tsx
└── ui/
    └── button/
        ├── index.ts // ユーティリティ関数等を定義
        └── index.tsx // Buttonコンポーネントを定義

tsconfig.json

{
  "include": [
    "**/*",
    "**/.server/**/*",
    "**/.client/**/*",
    ".react-router/types/**/*"
  ],
  "compilerOptions": {
    "lib": ["DOM", "DOM.Iterable", "ES2022"],
    "types": ["node", "vite/client"],
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "rootDirs": [".", "./.react-router/types"],
    "baseUrl": ".",
    "paths": {
      "~/*": ["./app/*"]
    },
    "esModuleInterop": true,
    "verbatimModuleSyntax": true,
    "noEmit": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true
  }
}

問題

routes/_index.tsxファイル内でimport { Button } from '~/ui/button'と記載した際、TS2305: Module "~/ui/button/index" has no exported member Buttonというエラーが発生しました。

原因

TypeScriptにおいてディレクトリを指定した場合、自動的にindex.tsを探すモジュール解決ルールが存在します。
そのため、同階層にindex.tsindex.tsxがそれぞれ存在すると、index.tsが優先され、index.tsxは無視されてしまいます。

解決方法

以下どちらかが解決方法になります。

  1. index.tsのファイル名を変更する
  2. buttonディレクトリにサブディレクトリを作成して、そっちでindex.tsを管理する

今回は2の方を採用し、ディレクトリ設計を以下のように変更しました。

apps/
├── routes/
│   └── _index.tsx
└── ui/
    └── button/
        ├── _logics/
        │   └── index.ts
        └── index.tsx

まとめ

ChatGPTに相談したところ、tsconfig.json内のinclude設定やresolveJsonModulefalseになっていないかと提案をしてくれましたが、いずれも間違っていなかったので、答えに辿り着くまでに少々時間がかかりました。

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