3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

importパスにエイリアスをかけてパス指定を楽にする

3
Last updated at Posted at 2019-12-29

はじめに

フロントエンドの開発で嫌という程、経験したのですがプロジェクトが大きくなり階層構造が増えれば増えるほどimportによるパスの指定が複雑になってきます。
特に、ユーザによってデザインの出し分けをする場合、どこのコンポーネントを表示させるか相対パスで指定するのは悲惨でした(笑)
その解決策の1つとして、パスにエイリアスをかけてパス指定を楽にする方法を紹介します。

通常のパス指定

通常パスを指定する場合、今いるファイルからの相対パスで指定します。

import Header from '../../../../../apartment/Header'
import Footer from '../../../../../house/Footer'

これでは、プロジェクトが大きくなって階層構造が増えるとパスの指定が非常にややこしくなります。

エイリアスを使ったパス指定

webpack.config.jsにaliasを指定します。

webpack.config.js
module.exports = {
  ...
  resolve: {
    alias: {
      '@apartment': path.resolve('src/components/designSet/apartment'),
      '@house': path.resolve('src/components/designSet/house'),
    }
  }
}

これで、エイリアスを指定しなかったパスを簡単に指定することができます。

// src/components/designSet/apartment/Headerのエイリアス
import Header from '@apartment/Header'
// src/components/designSet/house/Headerのエイリアス
import Footer from '@house/Footer'

解決

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?