LoginSignup
8
9

More than 5 years have passed since last update.

[React][TypeScript]絶対パスでimportできるようにする

Last updated at Posted at 2019-02-12

概要

  • create-react-appで作ったTypeScriptプロジェクトで絶対パスでファイルをimportできるようにする

手順

環境変数の設定

  • .envに記載するか起動スクリプトに追加する
.env
NODE_PATH=.
package.json
{
  // ...
  "scripts": {
    "start": "NODE_PATH=. react-scripts start",
    "build": "NODE_PATH=. react-scripts build",
    "test": "NODE_PATH=. react-scripts test",
    // ...
  },
  // ...
}

tsconfig.paths.jsonの作成

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

tsconfig.jsonへ設定追加

tsconfig.json
{
  // ...
  "extends": "./tsconfig.paths.json",
  // ...
}

結果

  • 以下のように絶対パスでimportできるようになる
  • VSCodeに補完もちゃんと効く
App.tsx
// ...
import Button from 'src/components/Button'
// ...
8
9
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
8
9