interface, type 차이점이 뭘까(Typescript)

비슷하지만 동일하지 않은 interface vs type

타입스크립트에서 타입을 선언하기 위해서는 interface 또는 type 키워드를 사용합니다.

각각의 선언 방식은 다음과 같으며 =의 유무만 다릅니다.

// interface
interface Team{
  name : string
}

// type
type Team = {
  name : string
}

그리고 타입의 확장 방법은 다음과 같습니다.

// interface
interface City extends Team {
  city : string
}

// type
type City = Team & {
  city : string
}

interface와 type의 가장 큰 차이점은 바로 선언적 확장(Declaration Merging) 기능인데요.

선언적 확장이란 이미 선언된 타입 선언에 필드를 추가하는 것입니다.

하나는 가능하고 하나는 가능하지 않은데 interface만 가능한 것이 특징입니다.

사용 방법은 다음과 같습니다.

interface Team {
  name : string
}

interface Team {
  manager : string
}

위와 같은 방법으로 이미 선언된 interface에 다시 필드를 선언할 수 있습니다.

하지만 type을 다음과 같은 방법으로 사용하면 에러가 발생합니다.

type Team = {
  name : string
}


// Error 발생 -> 'Duplicate identifier 'Team'
type Team = {
  manager : string
}

추가로 type은 원시형(number, string 등) 데이터를 다른 이름으로 지정해서 사용할 수 있지만 interface는 불가능합니다.

자세한 내용은 다음 코드와 같습니다.

//type으로 원시형 데이터의 이름을 지정
type NameDataType = string;

const printName = (name : NameDataType ) => {
  console.log(name);
}

//interface는 불가
interface NameType extends string {
}

차이점을 신경써도 되지 않을 상황이라면 취향에 따라 선택하면 되지만 기본적으로는 interface를 쓰면 큰 문제가 없다고 합니다.

참고 : typescript 공식 문서

Emotion(Styled), Props 전달하기(Typescript)

Typescript와 함께 동적 CSS 스타일 사용하기
import styled from "@emotion/styled";

const StyledPropsTest = styled.div`
  width: 120px;
  height: 40px;
  font-size: 25px;
  background: ${(props) => (props.testProps ? "blue" : "red")};
  color: white;
`;

const StyledTest = ({testprops}) => {
  return(
    <StyledPropsTest testProps={testprops}>Prop Test</StyledPropsTest>
  )
}

export default StyledTest;

컴포넌트 내부에서 사용하는 변수를 CSS에 전달하여 동적 스타일을 적용하기 위해서는 위와 같이 props를 전달하는 방법이 있습니다.

하지만 Typescipt를 사용하여 custom props를 사용하면 다음과 같은 에러를 만나게 됩니다.

(property) testProps: boolean
Type ‘{ children: string; testProps: boolean; }’ is not assignable to type ‘IntrinsicAttributes & { theme?: Theme | undefined; as?: ElementType<any> | undefined; } & ClassAttributes<HTMLDivElement> & HTMLAttributes<…>’.
Property ‘testProps’ does not exist on type ‘IntrinsicAttributes & { theme?: Theme | undefined; as?: ElementType<any> | undefined; } & ClassAttributes<HTMLDivElement> & HTMLAttributes<…>’.ts(2322)

이는 타입스크립트에서 props의 타입을 체크하기 때문인데요.

다음과 같이 간단하게 <{data:type}>의 타입 단언(Type Assertion)으로 해결할 수 있습니다.

const StyledPropsTest = styled.div<{testProps:boolean}>`
  width: 120px;
  height: 40px;
  font-size: 25px;
  background: ${(props) => (props.testProps ? "blue" : "red")};
  color: white;
`;

다음과 같이 에러가 사라진 것을 확인할 수 있습니다.

leaflet, 반복되는 지도에 marker 표시하기(react)

맵 축소 시 반복되는 지도에 Marker 반영하기

다른 옵션을 설정하지 않는 한 맵을 최대로 축소하면 다음과 같이 지도가 반복되어 나타납니다.

여기서 맵을 오른쪽이나 왼쪽으로 넘겨서 중심을 바꿔도 Marker는 그대로 있습니다.

하지만 맵 렌더링 시 다음과 같이 ‘worldCopyJump’ 옵션을 넣어주면 중심이 이동하더라도 기존의 Marker를 모두 표시할 수 있습니다.

<MapContainer
   center={[35.102, 129.067]}
   zoom={5}
   scrollWheelZoom={true}
   worldCopyJump
>

옵션 하나만으로 맵을 이동하면 Marker도 이동하여 같은 좌표에 표시되는 것을 확인할 수 있습니다.

leaflet 맵 표시 언어 변경

지도 데이터 서버 변경하기

leaflet의 기본 맵은 각 지역마다 현지 나라의 언어로 표기되어 한국 맵은 한국어, 일본 맵은 일본어, 프랑스 맵은 프랑스어로 표기되어 있습니다.

하지만 전체 맵을 영어로 표기하고 싶거나 산맥, 해양 등 용도에 맞게 지도의 이미지를 변경하고 싶을 때는 아래 링크에서 원하는 맵의 유형과 서버를 확인하여 서버만 변경해주면 됩니다.

1. 링크에서 서버 확인

http://leaflet-extras.github.io/leaflet-providers/preview/

링크에 접속하면 다음과 같은 화면입니다.

초록색 네모칸에서 서버 정보, 빨간색 네모칸에서 맵의 종류 샘플을 볼 수 있습니다.

샘플로 OpenStreetMap.France를 적용해보도록 하겠습니다.

빨간 네모칸에서 OpenStreetMap.France을 선택하면 초록 네모칸에 서버 정보가 표시됩니다.

‘https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png’

‘&copy; OpenStreetMap France | &copy; <a href=”https://www.openstreetmap.org/copyright”>OpenStreetMap</a> contributors’

이 두 부분만 코드에서 변경해주면 바로 적용이 됩니다.

2. 코드 적용

import { MapContainer, TileLayer, useMap, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { icon } from "leaflet";
const Icon = icon({
  iconUrl: "marker-icon.png",
  iconSize: [16, 16],
  iconAnchor: [12, 16],
});

const MyMap = () => {
  return (
    <MapContainer
      center={[37.56675, 126.97842]}
      zoom={10}
      scrollWheelZoom={true}
      style={{ width: "500px", height: "500px" }}
    >
      <TileLayer
        attribution='&copy; OpenStreetMap France | &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png"
      />
      <Marker position={[37.56675, 126.97842]} icon={Icon}>
        <Popup>서울시청이에요.</Popup>
      </Marker>
    </MapContainer>
  );
};

export default MyMap;

설정에 따라 변경된 맵과 언어를 확인할 수 있습니다.

CSS, calc()를 사용해 main(body) 높이 자동 설정하기

CSS에서 calc 메서드 사용하기

CSS에서 calc() 메서드를 사용하면 window 창의 사이즈 변경에 따라 자동으로 길이를 계산할 수 있습니다.

header, main, footer의 레이아웃을 나눌 때 main에서 calc()를 사용하게 되면 윈도우 창의 크기가 줄어들어도 main의 내용이 잘릴 염려 없이 가변적으로 창의 크기에 맞게 표현할 수 있습니다.

1. 필요성

예를 들면 다음과 같은 상황에서 유용합니다.

위와 같은 화면이 있을 때 윈도우 창의 사이즈를 줄이면(resizing) 가운데 main의 스크롤을 끝까지 내려도 데이터가 모두 표시되지 않을 때가 있습니다.

스크롤을 끝까지 내렸지만 이렇게 r 까지만 표시되고 아랫부분은 짤려서 표시되지 않습니다.

이런 상황에서 main의 div 높이를 계산하여 자동으로 조절해주면 다음과 같이 윈도우가 리사이징 되더라도 화면이 짤리지 않고 유지되는 것을 볼 수 있습니다.

2. 적용하기

main div의 높이(height)에 calc() 메서드를 사용하여 ‘뷰 높이(vh) – 나머지 공간’을 해주면 됩니다.

다만 전달값의 +, – 앞 뒤에는 반드시 공백을 삽입해야 합니다.

// OK
height: calc(100vh - 300px);

// 에러(공백 없음)
height: calc(100vh-300px);

결과는 다음과 같습니다.

Next.js + Leaflet(OSM) Marker 표시하기

Next.js에서 Leaflet Marker 이미지 로딩하기

React-leaflet에서 제공하는 기본 설정 방법에 따라 leaflet 코드를 구현하여도 맵은 표시되지만 Marker 이미지는 깨져서 표시됩니다.

Next.js에서 이미지는 Next/image와 이미지 상대 주소를 import하여 사용하면 잘 로딩이 되지만 상대 경로 url을 직접 사용하면 작동하지 않습니다.

예를 들면 다음과 같은 상황입니다.

import Image from "next/image";
import logo from "../../styles/images/logo.png";

//작동함
<Image src={logo} alt="logo />

//작동하지 않음
<Image src={"../../styles/images/logo.png"} alt="logo" width="100px" height="100px" />

이는 Next.js에 정해진 폴더 규칙이 있기 때문인데요. 만약 경로를 사용해 이미지나 파일을 가져오고 싶다면 public 폴더를 이용해야 합니다.

빌드 후 기본 폴더는 public이므로 public 폴더 내 logo.png 파일을 넣는 경우 /logo.png로 접근이 가능합니다.

import Image from "next/image";

<Image src={"/logo.png"} alt="logo" width={"100px"} height={"100px"} />

Marker 이미지 표시하기

이를 참고하면 Marker 이미지 부분도 icon을 사용해서 응용할 수 있습니다.

public 폴더 내 images 폴더를 만들고 logo.png 파일을 넣은 뒤 다음과 같이 사용합니다.

import { MapContainer, TileLayer, useMap, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { icon } from "leaflet";

const Icon = icon({
  iconUrl: "images/logo.png",
  iconSize: [24, 24],
  iconAnchor: [12, 24],
});

const MyMap = () => {
  return (
    <MapContainer
      center={[37.56675, 126.97842]}
      zoom={10}
      scrollWheelZoom={true}
      style={{ width: "500px", height: "500px" }}
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[37.56675, 126.97842]} icon={Icon} >
        <Popup>서울 시청</Popup>
      </Marker>
    </MapContainer>
  );
};

export default MyMap;

Next.js + Leaflet(OpenStreetMap) 초기 설정하기

Next.js와 leaflet이 만나기 위해서는 참고해야 할 사이트가 많습니다.

leafletjs.com
react-leaflet.js.org
openstreetmap.org

간략하게 정리해보겠습니다.


1. 라이브러리 설치

Next.js + Typescript는 설치되었다고 가정하겠습니다.(관련 포스팅 클릭)

npm i leaflet react-leaflet

Typescript 지원을 위한 라이브러리도 설치합니다.

npm i -D @types/leaflet

2. 코드 구현하기

다음과 같이 컴포넌트를 생성합니다.

import “leaflet/dist/leaflet.css”; 를 설정하지 않으면 맵이 깨져서 표시가 되고 style에 사이즈를 설정하지 않으면 하얀 화면만 나오니 두 부분 모두 주의해야 합니다.

scrollWheelZoom은 스크롤 확대/축소 기능을 설정합니다.

import { MapContainer, TileLayer, useMap, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";

const MyMap = () => {
  return (
    <MapContainer
      center={[37.56675, 126.97842]}
      zoom={10}
      scrollWheelZoom={true}
      style={{ width: "500px", height: "500px" }}
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[37.56675, 126.97842]}>
        <Popup>서울 시청</Popup>
      </Marker>
    </MapContainer>
  );
};

export default MyMap;

별도의 컴포넌트를 생성하는 이유는 관리를 위한 분리도 있지만 Next.js의 특성상 서버 렌더링 시 window 전역 객체에 접근할 수 없는 문제로 인해 발생하는 에러를 해결하기 위해서입니다.

DOM이 생성된 뒤 실행되는 useEffect를 사용하거나 레이지 로딩 기능인 dynamic을 사용할 수 있으며 여기서는 dynamic 기능을 사용하겠습니다.

같은 위치에 다음 컴포넌트를 생성합니다.

import dynamic from "next/dynamic";

const MyMap = dynamic(() => import("./MyMap"), { ssr: false });

const ShowMap = () => {
  return <MyMap />;
};

export default ShowMap;

이것으로 기본 구현은 완료되었으며 다음과 같이 맵을 호출하면 됩니다.

<ShowMap />

결과는 다음과 같습니다.

이것으로 Next.js에서 Leaflet을 사용하기 위한 설정이 완료되었지만 Marker 이미지가 깨지는 현상이나 언어 설정 등 추가할 부분이 많습니다.

해당 내용은 다른 포스트에서 다루도록 하겠습니다.

리액트, 리렌더링 시 CSS도 함께 리로드하는 방법(feat.animation)

컴포넌트 리렌더링 시 CSS도 함께 리렌더링하도록 만들기

리액트는 내부 로직에 따라 불필요한 렌더링을 최소화하도록 되어있지만 때로는 이 로직이 의도하지 않는 방식으로 작동할 때가 있습니다.

특히 애니메이션 효과를 줄 때 한 번만 실행되고 마는 것이 아니라 클릭 시마다 애니메이션이 동작하도록 만들고자 할 때 다음 방법을 유용하게 사용할 수 있습니다.

원리는 간단합니다.

리액트 컴포넌트는 state가 변경될 때마다 리렌더링을 실행하므로 클릭 시마다 state 값에 변경을 주면 됩니다.

예를 들어 다음 컴포넌트의 이미지를 확인해 보겠습니다.

const ColorChange = ({ color }) => {
  const DisplayBox = styled.div`
    width: 300px;
    height: 300px;
    display: flex;
    background: ${color};
    animation: change 3s;

    @keyframes change {
      0% {
        transition-timing-function: cubic-bezier(1, 0, 0.2, 0.5);
      }
      0% {
        width: 0;
      }
    }
  `;

  return <DisplayBox></DisplayBox>;
};

export default ColorChange;

---------------------------------------------------------------
컴포넌트 호출
<ColorChange color={color} /> 

red, green을 번갈아가며 누르면 컴포넌트에 전달되는 state가 변경되므로 컴포넌트가 리렌더링되면서 애니메이션이 동작합니다.

하지만 red인 상태에서 다시 red를 한번 더 누르면 애니메이션은 동작하지 않습니다.

그럼 클릭마다 CSS가 리렌더링되어 애니메이션이 작동하도록 하려면 어떻게 해야 할까요?

단순하게 클릭마다 전달되는 state의 값이 변경되도록 해주면 됩니다.

예를 들어 다음과 같이 컴포넌트 key 속성으로 임의의 값을 생성하여 전달합니다.

const [randomData, setRandomData] = useState(Math.random());

//버튼 클릭 시 호출 함수
const changeColor = () => {
     // 색상 변경 작업
     .......
     // 임의의 값 생성
     setRandomData(Math.random());
}

<ColorChange color={color} key={randomData} /> 

전달되는 color 값의 변경을 감지하여 리렌더링이 발생하고 그에 따라 CSS animation도 리로드되지만 계속 같은 버튼을 누르면 동일한 color 값이 전달되기 때문에 변경을 감지하지 못해 리렌더링이 되지 않는 원리입니다.

따라서 클릭 시 color 값은 변경되지 않더라도 key 값을 계속 변경하면 리액트는 컴포넌트 변경을 인식하여 계속 컴포넌트와 CSS를 리렌더링하게 됩니다.


렌더링은 최대한 리액트에게 맡기고 불필요한 렌더링은 최소화하되 위와 같이 필요한 부분에만 부분적으로 적용하도록 해야 합니다. 이를 위해서는 작동 방식의 이해가 필요합니다.

Next.js + Typescript + Emotion + Tailwind 환경 구축하기

Next.js에서 Emotion과 TailwindCSS를 함께 사용하기 위한 설정

1. Next.js 설치

다음 명령을 사용해 Next.js의 최신 버전 + typescript를 설치한다.

npx create-next-app@latest --ts

아래 명령어로 설치 및 버전을 확인한다.

npx next -v

2. emotion 관련 라이브러리 설치

emotion 관련 라이브러리를 설치한다.

npm i @emotion/react @emotion/styled @emotion/css @emotion/server

3. tailwind, twin.macro 라이브러리 설치

tailwind, twin.macro 관련 라이브러리를 설치하고 devDependencies에 추가한다.

npm i twin.macro tailwindcss postcss@latest autoprefixer@latest @emotion/babel-plugin babel-plugin-macros --save-dev

config 파일 생성을 위해 다음 명령어를 사용한다.

tailwind.config.js를 사용하면 입맛에 맞게 사용자 지정 스타일을 사용할 수 있다.

npx tailwindcss init -p
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

styles/globals.css의 상단에 다음 코드를 추가한다. (HTML 태그 내에서 인라인으로 tailwind를 사용 가능하게 함)

@tailwind base;
@tailwind components;
@tailwind utilities;

4. .babelrc 생성

twin.macro의 사용이 가능하도록 plugin 설정을 해야 하므로 .babelrc 파일을 생성한다.

내부 설정은 다음과 같다.

{
  "presets": ["next/babel"],
  "plugins": ["babel-plugin-macros"]
}

5. 작동 테스트

emotion 및 emotion +tw(tailwind) 작동을 테스트한다.

아래 코드를 pages/index.tsx에 작성하고 npm run dev로 실행한다.

import type { NextPage } from "next";
import styles from "../styles/Home.module.css";
import styled from "@emotion/styled/macro";
import tw from "twin.macro";

const Input = tw.input`
    text-center border h-28
`;

const MyDiv = styled.div`
  background: gold;
  font-size: 5rem;
  margin-top: 10px;
`;

const Home: NextPage = () => {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>
          <Input placeholder="box" />
          <MyDiv>Test Text</MyDiv>
        </h1>
      </main>
    </div>
  );
};

export default Home;

결과는 다음과 같다.


관련 링크

nextJS https://nextjs.org/

tailwindCSS https://tailwindcss.com/

emotion https://emotion.sh/docs/introduction

twin.macro https://github.com/ben-rogerson/twin.macro#readme

Angular npm 모듈 설치 시 npm ERR! Found: @angular/core 에러 해결

gyp verb `which` failed Error: not found: python2 등 에러 다발

앵귤러 프로젝트를 가져와서 npm install로 모듈 설치 시 dependency 에러가 발생하였다.

현재 사용하는 nodejs 버전은 16!

파이썬 관련 에러 문구도 있어 파이썬도 설치해보고…

npm install –save –legacy-peer-deps

npm install –global –production windows-build-tools

npm i node-pre-gyp

npm i sqlite3

npm install -g –unsafe-perm node-sass

위 방법을 사용해 봤지만 아무것도 되지 않았다.


nodejs 버전을 16에서 14로 변경하여 설치하고 npm install –legacy-peer-deps 을 사용하니 간단히 해결되었다.