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

ts-node で実行時に tsconfig.json の paths(alias) 設定が効かない

More than 1 year has passed since last update.

環境

ディレクトリ構造

tree
 .
├── index.ts
└── helpers
    ├── foo.ts # {foo: ...}
    └── bar.ts # {bar: ...}

依存インストール

yarn add -D typescript ts-node
yarn run tsc --init

TypeScript 設定

helpers/fooという感じでインポートできるようにこんな感じに設定。(この辺の設定について |> TypeScriptでaliasなパスでmoduleをimportできるように)

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

確認ファイル

index.ts
import {foo} from 'helpers/foo';
import {bar} from 'helpers/bar';

こんな感じで、yarn run ts-node index.tsとすればできる…ハズだった。

なんかできない

stderr
Error: Cannot find module 'helpers/foo'

ググる

おー、tsconfig.json/paths not working with ts-nodeというイシューがありました。

とりあえずこのtsconfig-pathsっていうの使ってみる…

yarn add -D tsconfig-paths
yarn run ts-node -r tsconfig-paths/register index.ts

ターーン!!?!?!!!!?!😇

解決しました。

nju33
① JavaScript (TypeScript) ② Bash ③ Rust な感じでやってます。最近はブログの方がメインです。
https://nju33.com
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
ユーザーは見つかりませんでした