본문 바로가기
FE/React

[React] craco 절대경로 설정 방법(TypeScript)

by suhyeon chae 2023. 1. 8.

매번 경로 계산하기 귀찮고 헷갈리기 때문에 craco를 사용하여 절대 경로 사용법에 대해 포스팅 하겠습니다.

 

// npm일 경우
npm i @craco/craco

// yarn일 경우
yarn add @craco/craco

 

1. project Root에서 craco.config.js 파일 생성

 

const path = require("path");
module.exports = {
    webpack: {
        alias: {
            "@": path.resolve(__dirname, "./src"),
        },
    },
};

 

 

2. tsconfig.json에서 baseUrl 설정

- 기본 Path를 src/* 로 설정

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/*": ["src/*"]
        },
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx"
    },
    "include": ["src"]
}

 

3. package.json 에서 scripts 변경

<원본>

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

아래와 같이 react-scripts -> craco로 변경

 

<변경>

    "scripts": {
        "start": "craco start",
        "build": "craco build",
        "test": "craco test"
    },

 

4. 실행

// npm인 경우
npm start

// yarn인 경우
yarn start

 

5. 사용

import { RouterProvider } from "react-router-dom";
import { RecoilRoot } from "recoil";
import ReactDOM from "react-dom/client";
import React from "react";

import "@/index.css";
import router from "@/router";

const root = ReactDOM.createRoot(
    document.getElementById("root") as HTMLElement
);
root.render(
    <React.StrictMode>
        <RecoilRoot>
            <RouterProvider router={router} />
        </RecoilRoot>
    </React.StrictMode>
);

@ : src를 말함

@/router : src/router 라는 뜻