728x90
반응형

1.  SVRG 설치

# NPM
npm install --save-dev @svgr/webpack

# Yarn 
yarn add --dev @svgr/webpack

 

 

 

2. next.config.js에  웹팩 구성 추가

[next.config.js에 추가하는 경우]

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ['@svgr/webpack'],
    })

    return config
  },
}

 

[next.config.mjs에 추가하는 경우]

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ['@svgr/webpack'],
    })

    return config
  },
};

export default nextConfig;

 

웹팩 구성으로 위의 코드를 추가하지 않으면 아래와 같은 오류가 발생합니다.

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

 

 

 

3. svg 이미지를 컴포넌트로 import


import Note from '@public/svgs/note.svg';

const TodoList: React.FC = () => {

  return (
    <>
      <Note/>
    </>
  );
};

export default TodoList;

 

 

 

*svg 관련해서 폴더 구조 잡을때 아래 글도 참고하기 좋았습니다. 추천드립니다.

Next.js 폴더/파일 구조 잡기 (miriya.net)

 

Next.js 폴더/파일 구조 잡기

주니어 개발자들이 가장 많이 물어보는 질문이 폴더 구조에 대해 묻는 것이다. 사실 이런 질문들은 항상 답이 정해져있다. “그때 그때 달라요” 아니 시발 그때 그때 다른게 어딨어? 하고 빡이

miriya.net

* 공식문서

https://blog.logrocket.com/import-svgs-next-js-apps/

 

How to import SVGs into your Next.js apps - LogRocket Blog

This article will explore the different methods you can use to import and use SVGs in a Next.js application.

blog.logrocket.com

 

728x90
반응형
728x90
반응형

사이드 프로젝트를 진행하던 중 코드블럭을 개발하게 되어서

코드에 하이라이트를 적용하기 위해 react-syntax-highlighter 라이브러리를 사용하였습니다.

 

1.  react-syntax-highlighter 설치

npm install react-syntax-highlighter

 

Typescript를 사용하시는 경우 아래 명령어도 실행해주세요.

npm install --save-dev @types/react-syntax-highlighter

 

 

2. 사용할 스타일 선택

https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/prism.html

 

React Syntax Highlighter Demo

 

react-syntax-highlighter.github.io

라이브러리 데모 페이지

 

데모 페이지에서 언어와 스타일을 바꿔가며 적용될 스타일을 미리 볼 수 있습니다.

 

 

 

3. 코드블럭 컴포넌트에 스타일 적용

'use client'

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { solarizedlight } from 'react-syntax-highlighter/dist/esm/styles/prism';

const CodeBlock: React.FC<{ code: string }> = ({code}) => {

  return (
    <>
      <div className="w-full">
        <div className="bg-blue-100 w-full h-9 rounded-t-lg px-4 py-2 text-sm text-gray-500 font-medium">index.js</div>
        <div className="bg-blue-50 w-full h-20 rounded-b-lg px-4 py-2 text-sm text-gray-800 font-medium">
          <SyntaxHighlighter language={"javascript"} style={solarizedlight}>
            {code}
          </SyntaxHighlighter>
        </div>
      </div>
    </>
  );
};

export default CodeBlock;

 

저는 solarizedlight 스타일의 하이라이트를 사용하였습니다.

 

코드블럭에서 코드가 실제로 출력되는 부분을 SyntaxHighlighter 태그로 감싸줍니다.

 

SyntaxHighlighter 태그에 코드를 구성하는 언어 정보와 스타일 정보를 props로 넘겨줍니다.

스타일 정보를 넘기지 않으면 기본 스타일로 적용됩니다.

 

 

4. 결과

기존 코드 블럭
필자가 선택한 하이라이트 스타일 적용
기본 하이라이트 스타일에서 배경색 제거

 

직접 선택한 스타일은 노란 배경색을 벗겨서 사용해봤는데 베이스가 회색이라 그런지 코드가 흐릿하게 보였습니다.

개인적으로 기본으로 제공하는 스타일이 제일 깔끔하고 좋았습니다.

728x90
반응형
728x90
반응형

📜 오류 발생

 

기존의 JavaScript 기반의 Next.js 프로젝트에 Typescript를 적용하던중 아래와 같은 오류가 발생하였다.

cannot use jsx unless the '--jsx' flag is provided

 

 

 

문제를 해결하기 위해 검색하던 중 VS Code에서Typescript 버전을 변경하면 해결된다는 자료들을 발견하였다.

 

 

F1 -> Typescript: Select TypeScript Version... 클릭

 

 

Use Workspace Version 클릭

 

 

 

 

Workspace Version으로 변경후 문제는 해결되었는데 VS Code's Version과 어떤 차이가 있길래 문제가 발생했는지 찾아보았다.

https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions

 

TypeScript Compiling with Visual Studio Code

Learn about TypeScript compiling with Visual Studio Code.

code.visualstudio.com

 

간단하게 요약하자면, 공식 문서에서 이야기하는 바는 아래와 같다. (초월 번역 했습니다)

 

VS Code는 자체적으로 최신 버전의 TypeScript가 기본으로 제공되는데, 이는 작업 파일을 컴파일하는 데 사용하는 TypeScript 버전과 별개이다. 일반적으로는 VS Code에서 기본으로 제공하는 TypeScript 버전을 사용할 수 있지만 문제가 생기면 작업 파일 버전으로 변경해야 할 수도 있다. (변경 방법은 위에 설명드린 내용과 같습니다)

728x90
반응형
728x90
반응형

📜 오류 발생

 

App Router 형식으로 되어있는 프로젝트에서 useRouter를 사용하는 도중에 아래와 같은 오류가 발생하였다.

 

Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

 

 

에러 메세지에 달려있는 공식문서 링크를 확인해보니 App Router를 사용중이라면 next/navigation 를 통해 import를 하면 된다고 안내하고있다. 오류가 난 시점에는 next/router 로 import 중이었기 때문에 오류가 나는 문제는 해결되었다.

If used in the app directory, migrate to the new hooks imported from next/navigation.

 

 

다만 나는 네비바에서 현재 위치한 페이지를 활성화 시켜서 보여주기 위해 현재 페이지 경로값이 필요했는데 next/navigation 로 불러온 useRouter에서는 현재 경로값을 찾기 어려웠다.

 

 

그래서 공식문서를 더 찾아보니 next/navigation 에서 usePathname으로 경로값을 받아와서 링크 활성상태를 비교하는것을 권장하고 있었다.

 

https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating

 

Routing: Linking and Navigating | Next.js

Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook.

nextjs.org

 

 

 

'use client'
import Link from "next/link";
import { usePathname } from 'next/navigation';
// import linkData from ...;

const Sidebar = () => {
  const pathName = usePathname();

  return (
    <nav>
      {linkData.map((link) => (
          <Link
            key={link.href}
            href={link.href}
            className={pathName === link.href ? "active" : "common"}
          >
            {link.label}
          </Link>
      ))}
    </nav>
  );
};

export default Sidebar;

 

usePathname을 사용하여, 현재 페이지 경로값과 일치하는 Link 태그에 활성화 표시를 할 수 있게 되었다.

 

728x90
반응형
728x90
반응형

1.  Node.js 설치

https://nodejs.org/en/download

 

Node.js — Download

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

 

 

2. Visual Studio Code 설치

* os에 맞게 잘 선택해서 설치하시길 바랍니다.

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

 

 

3. Visual Studio Code에서 프로젝트 관리 폴더 열기

파일 > 열기 > 미리 생성해둔 폴더 열기

visual studio code에서 quickjs 폴더가 열린 상태

 

 

 

4.  터미널에 프로젝트 생성 명령어 입력

터미널 > 새 터미널 > 열린 터미널에 명령어 입력

npx create-next-app@latest .

설치시 본인이 개발할 프로젝트에 맞게 답변

 

 

5. 프로젝트 실행

생성된 프로젝트 폴더로 다시 이동합니다. ( 파일 > 열기 > 방금 생성된 프로젝트 폴더 )

 

터미널을 다시 열고 실행 명령어를 입력합니다.

npm run dev

 

127.0.0.1:3000 주소로 프로젝트가 열립니다. (localhost:3000도 동일한 주소라고 생각하시면 됩니다)

로컬에서 프로젝트 실행

 

 

Would you like to run the app on another port instead? (Y/n)

위와 같은 문구가 뜬 경우에는 프로젝트에 설정된 실행 포트번호를 사용하고 있는 프로젝트가 있다는 뜻입니다.

설정 변경이 없었다면, 3000번 포트번호를 사용중인 프로젝트가 있을 수 있습니다.

 

Y 입력시 : 프로젝트 실행 포트번호가 아닌 다른 포트번호로 프로젝트를 실행시켜줍니다.

n 입력시 : 취소

 

 

6. 프로젝트 종료

프로젝트를 종료하고 싶다면 터미널에 Ctrl+C를 입력하시면 됩니다.

 

 

 

 

728x90
반응형
728x90
반응형

1.  Node.js 설치

https://nodejs.org/en/download

 

Node.js — Download

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

 

 

2. Visual Studio Code 설치

* os에 맞게 잘 선택해서 설치하시길 바랍니다.

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

 

 

3. Visual Studio Code에서 프로젝트 관리 폴더 열기

파일 > 열기 > 미리 생성해둔 폴더 열기(react)

visual studio code에서 react 폴더가 열린 상태

 

 

 

4.  터미널에 프로젝트 생성 명령어 입력

터미널 > 새 터미널 > 열린 터미널에 명령어 입력

npx create-react-app 프로젝트 이름

프로젝트 생성중 화면

 

 

5. 프로젝트 실행

생성된 프로젝트 폴더로 다시 이동합니다. ( 파일 > 열기 > 방금 생성된 프로젝트 폴더 )

 

터미널을 다시 열고 실행 명령어를 입력합니다.

npm run start

 

127.0.0.1:3000 주소로 프로젝트가 열립니다. (localhost:3000도 동일한 주소라고 생각하시면 됩니다)

로컬에서 프로젝트 실행

 

 

Would you like to run the app on another port instead? (Y/n)

위와 같은 문구가 뜬 경우에는 프로젝트에 설정된 실행 포트번호를 사용하고 있는 프로젝트가 있다는 뜻입니다.

설정 변경이 없었다면, 3000번 포트번호를 사용중인 프로젝트가 있을 수 있습니다.

 

Y 입력시 : 프로젝트 실행 포트번호가 아닌 다른 포트번호로 프로젝트를 실행시켜줍니다.

n 입력시 : 취소

 

 

6. 프로젝트 종료

프로젝트를 종료하고 싶다면 터미널에 Ctrl+C를 입력하시면 됩니다.

 

 

 

 

728x90
반응형

'Frontend > React' 카테고리의 다른 글

[react] 다국어 처리(i18n) - 클래스형 컴포넌트  (0) 2024.01.25

+ Recent posts