Help us understand the problem. What is going on with this article?

create-react-appで作ったTypeScriptプロジェクトで絶対パスでのimportをしたい

概要

絶対パスでimportしたい。

import Post from  '../../components/Post' 

import Post from  'components/Post'

やり方

.envの設定

.envの中を下記のようにすることで、Webpack側でaliasが効くようになります。

NODE_PATH=src

ref) https://github.com/facebook/create-react-app/issues/2188#issuecomment-302040874

.tsconfigの設定

これだとTypeScript側が認識してくれないため、.tsconfigでもpathを貼る必要があります。

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

しかし、ただ書き加えてもreact-scripts startすると消されてしまいます...。
どうやらreact-scriptsが勝手に消してくるらしい。

そのため別ファイルに定義し、それをextendsすることでそれを回避します。

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

ref) https://stackoverflow.com/questions/53794875/how-to-configure-react-script-so-that-it-doesnt-override-tsconfig-json-on-star

おわり

これで絶対パスで読み取れるようになりました!

import Post from  'components/Post'

Webpackerもそうですが、こういうのは導入は便利でも改変しづらいのが面倒ですね。
生が一番です。

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした