40
14

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-11-12

環境

ディレクトリ構造

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

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

解決しました。

40
14
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
40
14