LoginSignup
19
10

More than 3 years have passed since last update.

VS Code + create-react-app v3でtsconfig.jsonのpathsを使用する

Posted at

やりたいこと

  • create-react-appで作ったプロジェクトで、
  • VS Codeの補完を有効にしつつ、
  • tsconfig.jsonpaths オプションに設定したaliasを使いたい。
  • 起動はデフォルトの react-scripts start

環境

  • react-scripts: 3.0.1
  • VS Code: 1.36.1
  • typescript: 3.5.2

答え

tsconfig.json

{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "baseUrl": "src",
    ...
  },
  ...
}
  • pathsは別ファイルに定義してextendsで読み込む。(ファイル名はなんでもいい)
    そうしないと react-scripts start した時に paths オプションが消される。

  • baseUrlは"src"にする。
    そうしないと Your project's `baseUrl` can only be set to `src` or `node_modules`. Create React App does not support other values at this time. と怒られる。

tsconfig.paths.json

{
  "compilerOptions": {
    "paths": {
      "components/*": ["./components/*"],
    }
  }
}
  • baseUrlが"src"なのでsrcからの相対パスにする。
    "components/*": ["./src/components/*"] にしちゃダメ

結論

importの相対パス地獄から解放されると同時にVS Codeの補完も使える。
VS Codeは天才なのでextendsで指定したファイルのpathsも読み込んでくれるらしい。
create-react-apppaths を消すのをやめろ。
create-react-appbaseUrl で "." を使用可能にしろ。

19
10
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
19
10