Webpack 별칭 등록

import 또는 require() 로 불러오는 모듈의 경로를 별칭(alias)으로 등록하면 "모듈 불러오기"가 수월해집니다.

const path = require('path')
const getAbsolutePath = (target) => path.resolve(__dirname, target)

module.exports = {
  // ...
  resolve: {
    // 생략 가능한 확장자
    extensions: ['.js', '.jsx', '.json'],
    // 절대 경로 별칭 등록
    alias: {
      modules: getAbsolutePath('src/modules/'),
      components: getAbsolutePath('src/components/'),
    }
  }
}

별칭을 등록하면 어렵게 불러왔던 모듈 경로를 손쉽게 불러올 수 있게 됩니다. (등록 전 → 등록 후 코드 확인)

import { createElement } from '../../modules/DOM'

일반 모듈 이름과 별칭 이름이 구분되길 원한다면? 다음과 같이 특수 문자를 사용해 등록할 수 있습니다.

alias: {
  '@components': getAbsolutePath('src/components/'),
  '@contexts': getAbsolutePath('src/contexts/'),
  '@pages': getAbsolutePath('src/components/'),
  '@hooks': getAbsolutePath('src/hooks/'),
  '@utils': getAbsolutePath('src/utils/'),
}

특수 문자 별칭을 등록한 후에는 다음과 같이 사용 가능합니다.

import App from '@components/App'

참고

Last updated