cra -> nextjs 고분분투기 - router, redux, sessionStorage ...
본문 바로가기

Frontend/React

cra -> nextjs 고분분투기 - router, redux, sessionStorage ...

현재 자바스크립트 생태계는 춘추전국 시대라 할 만하다.
지금 이 순간에도 새로운 패키지가 엄청나게 쏟아져 나온다.
기존에 가장 좋은 방법이라 여겼던 것이 새로운 방법으로 대체되는 경우도 있다.
그만큼 우리에게는 하나의 문제를 해결하기 위한 다양한 선택지가 있고,
이들 가운데 하나를 선택해야하는 상황을 자주 맞딱뜨리게된다. ...
- 실전 리액트 프로그래밍

 

기존 CRA에서 만든 프로젝트를 웹팩셋팅하고 옮기려했는데 nextjs를 추천받았다.

오호 이거 쉽겠는데라고 생각했던것은 나의 오산

에러들이 아주 빵빵터지는데..

엉엉... 울고싶다.

 

Router

next 강의쪼금들어보니 라우터 선언따위 필요없었음 ^^ 이때만해도 오 훨씬 간편한데?! 하며 수월할줄알았지..

하지만 태그들에 삼항연산자를 쓰면서 문제가 발생했다. 각각 다른 href경로를 넣었음에도 불구하고 계속 자기마음대로 경로가 바뀌는 문제가 발생했다. 별수 없이 onclick을 달고 router.push를 써서 해결

import { useRouter } from 'next/router'

export default example function(){
const router = useRouter()
return(
...
        <div onClick={() => router.push('/myPage')}>
          내정보
        </div>
)

https://nextjs.org/docs/api-reference/next/router

 

next/router | Next.js

Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook.

nextjs.org

 

Redux

공식문서에는 redux toolkit만 있는데 나는 redux 코드란말이지.. 일단 <React.Strict>태그랑 Redux를 크롬에서보기위해 넣었던 코드는 싹지워보니까 일단 됨

요새는 Redux대체할만한 툴들이 많이생긴것같다. 훨씬 간편한 Recoil도있고..

 

styled-coponents

공식문서하라는대로 하기는 했는데..

기존 _document 코드무시하고 걍 샘플코드 복사 붙여넣기함

https://styled-components.com/docs/advanced#nextjs

 

Absolute Path 절대경로

나의경우는 타입스크립트를 포함하였는데

가령 import {...} from '../../src/component/...'가 아니라 'src/component/...'이런식으로하고싶어서 tsconfig.ts에서 baseUrl을 추가하였다.

// tsconfig.json or jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "."
  }
}

https://nextjs.org/docs/advanced-features/module-path-aliases

 

만약에 eslint에서 undable to resolve path to module이라는 에러가 난다면

eslintrc.json에 아래와 같은 코드를 추가한다. 나같은경우는 'src/...'로 시작하기때문에 'src/'를 추가하였다.

{
    ...
    settings: {
        ...
        'import/resolver': {
            node: {
                extensions: ['.js', '.jsx', '.ts', '.tsx'],
                moduleDirectory: ['node_modules', 'src/'],
            },
        },
    }
}

https://stackoverflow.com/questions/55198502/using-eslint-with-typescript-unable-to-resolve-path-to-module

서버 port 변경

CRA는 예를들어 3000이 열려 있으면 3001로 자동으로 바꿔주던뎅..

npm run dev -- -p 3005

일단 강제로 port를 변경해서 클라이언트 개발단서버를 열었으나 나중에 배포할때가 걱정됨..

 

Nextjs왈: SessionStorage가 뭐야??

아니 nextjs는 자바스크립트라면서 sessionStorage를 모른다네..? 이런 황당한경우가??

sessionStorage is not defined //sessionStorage가 뭐야??
localStorage is not defined //localStorage가 뭐야??
window is not defined//window가 뭐야???

window. 을 붙였는데 window가 뭐야?? 이러고있네.. ㅠ

구글을 쳐보니 react나 nextjs에서는 이런식으로 if문 안에다가 넣어줘야한다고..

생각해보니 cra라서 에러없이 사용할 수 있지않았을까? 이런생각도 들었다.

if (typeof window !== 'undefined') {
  console.log('You are on the browser')
  // 👉️ can use localStorage here
} else {
  console.log('You are on the server')
  // 👉️ can't use localStorage
}

 

https://bobbyhadz.com/blog/javascript-referenceerror-localstorage-is-not-defined

 

Solve - localStorage is not defined Error in JavaScript | bobbyhadz

To solve the "ReferenceError localStorage is not defined" error, make sure to only use the `localStorage` object in the browser. The `localStorage` property is defined on the `window` object and is not available on the server - e.g. in Node.js or when usin

bobbyhadz.com

 

그럼에도 Nextjs를 하고싶은 이유

한번 신세계를 맛보면 다시 과거로 회귀하기가 싫어진다.

console.log가 터미널에 찍히다니 찍히다니!!!

그밖에 여러 기능을 제공해준다고 한다.

- 이미지 최적화

- 랜더링 최적화

- 캐시

- .env 라는 파일에서 노드 환경구축

- API proxy 수행

- 도커 이미지를 말기도 수월함

 

 

느낀점

create-react-app이라는 안전지대를 벗어나 야생의 세계를 만난느낌이었다.(마치 부모님집에서 독립해 서울로 상경한느낌이랄까) 아마 웹팩을 했어도 같은 상황에 부딪히지 않았을까 싶다. 언제까지 안전지대에만 있을 수는 없지.. 혼자서 문서를 뒤지며 구글을 찾아보며 며칠전의 햇병아리의 나보다는 쪼금 성장한것같아서 뿌듯하다...

반응형