본문 바로가기
컴퓨터/인터넷

Typescript로 만든 react 프로젝트에서 경로 별칭 사용하기..

by 신규하 2020. 11. 23.

react 프로젝트를 진행하다 보면 아래와 같이 경로가 복잡해 지는 경우가 있습니다.

 

import MyComponent from "../../../../../components/MyComponent"

이럴때 간단하게 별칭을 사용해서 아래와 같이 줄이는 방법을 소개 합니다.

import MyComponent from "@/components/MyComponent"

tsconfig.json에 아래와 같이 추가를 해 줍니다.

{
  "compilerOptions": {
    // 추가 룰
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"],
    }
  }
}

create-reacte-app으로 프로젝트를 만들었다면, npm run eject를 해 주시고 tsconfig-paths-webpack-plugin을 설치해 줍니다.

npm i -D tsconfig-paths-webpack-plugin

그리고, webpack.config.js 파일에  아래와 같은 내용을 추가해 줍니다.

const TsconfigPathsPlugin = require(‘tsconfig-paths-webpack-plugin’);

module.exports = {
  // 추가
  resolve: {
    plugins: [new TsconfigPathsPlugin()],
  }
}

eslint를 사용한다면 eslint.json에 아래의 룰을 추가해 줍니다.

{
  "rules": {
    "import/no-unresolved": "off"
  }
}

 

 

댓글