2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[事件簿] Parcelでtypescriptのpathsを使おうとしてハマった事件

Posted at

In my case

状況

  1. React使ったWebアプリケーション作る。
  2. ビルドはWebpackめんどくさいのでParcel使います。
  3. TypeScriptによる開発です。

フォルダ構成

├── index.html
├── src
│   ├── app
│   │   └── index.tsx
│   └── hoge.tsx
├── package.json
└── tsconfig.json

わいの考え 「tsのコードはsrcに全部入れて、エントリーポイントになるhtmlはsrcと同じ階層でええかな」

① index.htmlで./src/app/index.tsxを読み込む

index.html
<script src="./src/app/index.tsx"></script>

./src/app/index.tsxの中で1つ上にあるhoge.tsxを読み込む

index.tsx
import hoge from '../hoge'

パス地獄になりたくないからこうしたい ↓

index.tsx
import hoge from '~/hoge'

~/が~srcにマッピングされるようにtsconfig.jsonを設定する

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

④ parcelでビルド

parcel ./index.html

デデーン

Cannot resolve dependency '~/hoge' at .....

パス解決できないエラーになる。

⑤ tsconfig.jsonの設定を変えてみる

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

⑥ ふたたびビルド

parcel ./index.html

デデーン

Cannot resolve dependency '~/hoge' at .....

パス解決できないエラーになる。

ちなみに

tsconfig.jsonrootDirに関しては

  • 指定なし
  • ./を指定
  • ./srcを指定

どのパターンだろうとダメ

⑦ 困る

parcelだとtsのpathsが使えない説?
調べてみると数年前はそういう問題があったようだ(githubのissuesに上がってた)
けど今はできるっぽい。

トライ&エラーの繰り返し

解決した方法

index.htmlsrcの中に移動したら解決した。

- ├── index.html
  ├── src
+ │   ├── index.html
  │   ├── app
  │   │   └── index.tsx
  │   └── hoge.tsx
  ├── package.json
  └── tsconfig.json
index.htmlの変更点
- <script src="./src/app/index.tsx"></script>
+ <script src="./app/index.tsx"></script>
ビルドコマンドの変更点
- parcel ./index.html
+ parcel ./src/index.html

tsconfig.jsonの設定は

こっちでも:

{
  ... 
  "baseUrl": "./",
  "paths": {"~/*":["src/*"]},
  ...
}

こっちでも:

{
  ... 
  "baseUrl": "./src/",
  "paths": {"~/*":["*"]},
  ...
}

どっちでもいけた。

エピローグ

とりあえずpathsは使えたし、これでひとまず困ることはない。

とは思うものの

html含めて全部同一フォルダに入れないといけない
それがparcelの仕様なのか

はたまた
複合的な理由でこうなってしまったのか

それは定かではない。

2
2
1

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?