Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

概要

  • 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'
// ...
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
10
Help us understand the problem. What are the problem?