14
4

More than 3 years have passed since last update.

【Typescript】baseUrlからインポートしたときのESLintエラーUnable to resolve path to module~ を解決する方法

Last updated at Posted at 2021-04-09

エラー

. 
├── dist/
├── node_modules/
├── src
│    ├── 
│    ├── 
│    ├── routes/
│    │    ├── 
│    │    └── foo/
│    │         └── hoge.ts
│    └── types/
│         └── index.d.ts
│   
├── .eslintrc.js
├── tsconfig.json
└── 他

src/routes/hoge.tssrc/typs/index.d.ts をインポートするとき

hoge.ts
import { fugafuga } from '../../types';

上のような相対パスで書いてもよいが、下のようにsrc/を起点としたパスで書きたかったので

hoge.ts
import { fugafuga } from 'types';

tsconfig.jsonにてbaseUrlを設定した

tsconfig.json(抜粋)
"compilerOptions": {
  "baseUrl": "./src"
}

これで問題なく読み込めたが、ESLintのエラーが出てしまった

hoge.ts
import { ExRequest } from 'types';
// Unable to resolve path to module 'types'.eslint(import/no-unresolved)

解決方法

eslint-import-resolver-typescript をインストールして

$ yarn add -D eslint-import-resolver-typescript

eslintrc.jsに設定を追加する

.eslintrc.js(抜粋)
settings: {
  'import/resolver': {
     typescript: { project: './' }
     // たぶんeslintrc.jsからtsconfig.jsonがあるディレクトリへの相対パス
},

これでESLintエラーは解決した。vscodeの拡張機能による赤い波線はVscodeを再起動すると消える。

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