LoginSignup
25
14

More than 5 years have passed since last update.

Angularでインポートパスを短縮する

Posted at

はじめに

このような、長ったらしいコンポーネントやサービスのimport文を...

import { LoginComponent } from './../../../auth/components/login/login.component';
import { LoginService } from '../../../auth/services/login.service';
import { DatePipe } from '../../lib/pipes/date.pipe';

次のようにスッキリさせる方法を紹介します。

import { LoginComponent } from '@auth/components/login/login.component';
import { LoginService } from '@auth/services/login.service';
import { DatePipe } from '@shared/lib/pipes/date.pipe';

やっていく

tsconfig.jsonののcompilerOptionsにある、baseUrlpathsというキーに設定を加えていきます。
app/tsconfig.app.jsonと間違えないように注意

tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
  // ...省略...
    "baseUrl": "src",
    "paths": {
      "@auth/*": ["app/auth/*"],
      "@shared/*": ["app/shared/*"]
    },
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

ここでは、モノレポっぽく@で始まる名前を使っていますが、使用しているライブラリなどのネームスペースと衝突しない限り自由に名前をつけることができます。

終わりに

今回紹介した内容は、Angularプロジェクト固有のものではなく、TypeScriptのモジュールシステムの機能を使った方法なので、様々なプロジェクトで応用できるかと思います。

参考

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