LoginSignup
4
4

More than 5 years have passed since last update.

Angular by TypeScript サブモジュール内でプロジェクトのsharedのimportをシンプルに記述する

Last updated at Posted at 2016-11-14

前提

ベースはangular-cliで作成したプロジェクトで、なんとなく下記のような構成(になるよね?)。
※今回の話題に関係ないファイルは省略
ちなみにsharedはプロジェクト全体で共有して使うモジュール。

projectRoot
├── src
│   └── app
│       ├── moduleA
│       │     └──components
│       │        └── hoge.component.ts
│       ├── moduleB
│       └── shared
│           └── services
│                ├── moge.service.ts
│                └── index.ts (export * './moge.service.ts')
└── tsconfig.json

問題点

hoge.component.ts内でMogeServiceをimportをしようと思うと

hoge.comopnent.ts
imoprt { MogeService } from '../../shared/services';

と書く必要がある。
moduleの外側への参照……
moduleって言ってるにくせに密結合な依存になってるようで個人的にすごい気持ち悪さがぬぐえない。

解決策

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "my-shared/*": [
        "app/shared/*"
      ]
    }
  }
}

これで

hoge.comopnent.ts
import { MogeService } from 'my-shared/services';

こう書ける!
これなら(オレオレ)ライブラリな感じでimportできてすっきり。
※逆に言うとライブラリと見分けが付くような名前を付けないと紛らわしいかも

なんならホントにライブラリとして公開することになっても(ならないだろうけど)コードの変更がほぼない。

参考

Module Resolution・TypeScript

4
4
1

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