[TIL] path alias & craco

JIEUN YANG·2023년 1월 11일
0

Absolute Path vs Relative Path

There are two ways to indicate path of files.
One is ‘Absolute Path’ and the other is ‘Relative Path’

Absolute Path is a method to show a file’s path with Root Directory like src

// Relative Path

import Checkbox from '../../components/Checkbox'
import Api from '../../../service/http/common/auth'

On the other hand **Relative Path** shows paths based on a current located in file and parent or child file could be differenciated from where the current file is.
// Relative Path

import Checkbox from '@/common/components/Checkbox'
import Api from '@/service/http/common/auth'

Both are okay, but I prefer setting Absolute path(full path) to Relative path
Because it’s more visible to track path of files and accessible anywhere.
But, If to use Relative Path, some settings should be done before using it in react
(I’ll introduce how to set Craco, so please find other instructions if you’d like to select ejection)



How to use Craco

1. Install craco library

Type **npm i @craco/craco** at terminal in your proejct

craco webpage

2. Make new file named craco.config.js and designate path alias

// basic alias setting 

const path = require('path')

module.exports = {
    webpack : {
        alias : {
            '@' : path.resolve(__dirname, 'src/') // import Api from "@/service/login";
        }
    }
}

All the paths starts from ‘@’ whenver modules are imported

  • craco.config.js file should be placed in roote path where the same location with package.json

3. Change scripts command to craco at package.json

"scripts": {
    "start": "craco start", // originally 'react-scripts start'
    "build": "craco build",
  },

4. Run react app in your Browser




Reference

https://helloinyong.tistory.com/325

profile
violet's development note

0개의 댓글