전반적 개요

2023. 11. 14. 01:51웹/next_js_리액트_타입스크립트

728x90
반응형

Next.js는 오픈 소스 웹 애플리케이션 프레임워크입니다. 웹 프런트엔드 라이브러리인 리액트를 기반으로 구현 및 개발됐습니다. 서버 사이드 렌더링이나 정적 웹사이트 생성 등, 리액트를 기반으로 웹 애플리케이션 개발에 편리하게 사용할 수 있는 기능을 추가했습니다. 리액트를 기반으로 하지만, 프런트엔드 뿐만 아니라 서버의 기능도 일부 갖고 있습니다.

 

  • 리액트로 웹 애플리케이션 만들 때 인기 있는 프레임워크 
  • 리액트 공식 문서에서도 Next.js 활용 권장
  • Next.js를 활용해 리액트의 기능을 서버 사이드에서 랜더링되는 애플리케이션으로 확장 가능

CSR vs. SSR


 

PWA(Progressive Web App)

프로그래시브 웹 앱(Progressive Web App)이라고 하며 웹과 네이티브 앱의 기능을 모두 갖춘 형태
웹처럼 URL로 접근하여 애플 스토어나 구글 스토어를 거치지 않고 모바일 디바이스 홈 화면에 바로 설치하여 사용이 가능하다는 것입니다. 설치하여 구동 시 상단에 URL 컨트롤을 감추어 일반적인 모바일 앱처럼 작동하게 만들 수도 있다.

모든 데이터를 기본적으로 캐싱하여 오프라인 상태에서도 데이터를 볼 수 있
구글 프로그레시브웹 앱 | 모질라 프로그레시브 웹 앱

 

기존 리액트 애플리케이션 구성 VS. Next.js 구성

Nexs.js가 React가 할 수 있는 영역을 커버하면서 더 많은 기능을 가지고 있으면서 제공을 한다.

라이브러리 vs. 프레임워크

Libraries and frameworks are code that someone else wrote
 to help you solve common problems while writing your application

Libraries
are to solve a specific problem in your app. For example:

Frameworks
Typically is a collection of libraries that work together in some opinionated way to help you build a fully functioning app.


타입스크립트

자바스크립트에 정적 타입 기능(↔ 동적 타입) 등을 탑재한 프로그래밍 언어.

현 시점에는 모던 프런트엔드 개발 프로그래밍 언어의 표준으로 자리 잡고 있음(앞으로는?)

Javascript + Type

 

자바스크립트와 비교로 타입스크립트 이해해보기

//자바스크립트
let a =3 +"5";
console.log(a) 
//결과 8

let b = 6;
b = "asdf";
console.log(b);
// 결과, asdb


//타입스크립트
let a:number =3 +"5"; //에러
console.log(a) 

let b:number = 6;
b = "asdf"; //에러, 
console.log(b);

타이스크립트 설치

// 타입스크립 설치
npm install -g typescript

 

타입스크립트 확장자는 "ts" [자바스크립트는 "js"]

타입의 종류

  • number
  • string
  • boolean
  • null
  • undefined
  • any
let a:number = 3
a ="asdfadf" //에러 발생, Type 'string' is not assignable to type 'number'.
let c:any = 4
c = "asdf" //에러 발생 안됨, 기존 자바스크립트 처럼 허용 됨.

let d :number | string = "asdfs"
d = 3
d = null // error 발생
// 배열
let e:string[] = ['apple','mongo']
let t:number[] = [1,2,3,4,5]
function addNumber (a:number, b:number):number {	
    return a+b	
}

let result:number
result = addNumber(3,7)
console(result)

타입스크립트 번역

tsc index.ts //tx을 js로 번역-> index.js

node index.js # 실행

tsconfig.json

타입스크립트를 자바스크립트로 변환을 위핸 설정 값.

{
 "compilerOptions": {

  "target": "es5", // 'es3', 'es5', 'es2015', 'es2016', 'es2017','es2018', 'esnext' 가능
  "module": "commonjs", //무슨 import 문법 쓸건지 'commonjs', 'amd', 'es2015', 'esnext'
  "allowJs": true, // js 파일들 ts에서 import해서 쓸 수 있는지 
  "checkJs": true, // 일반 js 파일에서도 에러체크 여부 
  "jsx": "preserve", // tsx 파일을 jsx로 어떻게 컴파일할 것인지 'preserve', 'react-native', 'react'
  "declaration": true, //컴파일시 .d.ts 파일도 자동으로 함께생성 (현재쓰는 모든 타입이 정의된 파일)
  "outFile": "./", //모든 ts파일을 js파일 하나로 컴파일해줌 (module이 none, amd, system일 때만 가능)
  "outDir": "./", //js파일 아웃풋 경로바꾸기
  "rootDir": "./", //루트경로 바꾸기 (js 파일 아웃풋 경로에 영향줌)
  "removeComments": true, //컴파일시 주석제거 

  "strict": true, //strict 관련, noimplicit 어쩌구 관련 모드 전부 켜기
  "noImplicitAny": true, //any타입 금지 여부
  "strictNullChecks": true, //null, undefined 타입에 이상한 짓 할시 에러내기 
  "strictFunctionTypes": true, //함수파라미터 타입체크 강하게 
  "strictPropertyInitialization": true, //class constructor 작성시 타입체크 강하게
  "noImplicitThis": true, //this 키워드가 any 타입일 경우 에러내기
  "alwaysStrict": true, //자바스크립트 "use strict" 모드 켜기

  "noUnusedLocals": true, //쓰지않는 지역변수 있으면 에러내기
  "noUnusedParameters": true, //쓰지않는 파라미터 있으면 에러내기
  "noImplicitReturns": true, //함수에서 return 빼먹으면 에러내기 
  "noFallthroughCasesInSwitch": true, //switch문 이상하면 에러내기 
 }
}

 

※ 윈도우에서는 "파워쉘"에서 하면 오류없이 컴파일 됨.

tsc -p [파일.tx]

타이스크립트 리액트 환결 설정

https://create-react-app.dev/docs/getting-started#creating-an-app

 

Getting Started | Create React App

Create React App is an officially supported way to create single-page React

create-react-app.dev

npx create-react-app my-app --template typescript

컴포넌트 타입스크립트 변환

타입을 만드는법

인터페이스(+extends)

interface OwnProps{
    info:Restaurant,
    changeAddress(address:Address):void,
}
interface OwnProps extends Menu{
    showBestMenuName(name:string):string
}

 

extends기능을 type로 상요할 때는 아래처럼 변경하면 됨.

type OwnProps = Menu &{
    showBestMenuName(name:string):string
}

type

export type Restaurant = {

    name:string;
    category:string;
    address:Address;
    menu:Menu;
}

export type Address ={
    city:string;
    detail:string;
    zipCode:Number;
}

export type Menu={
    	name:string;
        price:number;
        category:string;
}

type에서 무언가 빼야할 경우

export type AddressWithoutZip = Omit<Address,'zipCode'>

위를 아래처럼 적을 수 있음.
export type AddressWithoutZip ={
    city:string;
    detail:string;
}

한가지를 선택해야 할때

export type RestaurantOnlyCategory = Pick<Restaurant,'category'>

API 응답값을 타입스크립 처리

export type ApiResponse<T>{
    data:T[],
    totalPage:number,
    page:number
}

export type RestaurantResponse =  ApiResponse<Restaurant>
export type MenuResponse =  ApiResponse<Menu>

 

전체적인 소스

App.tsx

import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';
import Store from './Store';
import { Restaurant, Address} from './model/restaurant';
import BestMenu from './BestMenu';

let data:Restaurant ={
  name : '누나네 식당',
  category:'western',
  address:{
    city:'incheoi',
    detail:'somewhere',
    zipCode:23425634
  },
  menu:[
    {
      name:"rose pasta",
      price : 2000,
      category:"PASTA"
    },
    {
      name:"garlic steak",
      price : 3000,
      category:"STEAK"
    }
  ]
}
const App:React.FC = ()=> {
  const [myRestaurant, setMyRestaurant] = useState<Restaurant>(data)
  const changeAddress =(address:Address)=>{
    setMyRestaurant({...myRestaurant,address:address})
  }
  const showBestMenuName =(name:string):string=>{
      return name
  }
  return (
    <div className="App">
      <Store info={myRestaurant} changeAddress={changeAddress}></Store>
      <BestMenu name="불고기피자" category="피자" price={1000} showBestMenuName={showBestMenuName} />
    </div>
  );
}

export default App;

 

컴포넌트 : BestMenu.tsx / Store.tsx

import React from "react";
import {Menu} from "./model/restaurant";

interface OwnProps extends Menu{
    showBestMenuName(name:string):string
}
// interface OwnProps extends Omit<Menu,'price'>{
//     showBestMenuName(name:string):string
// }
const BestMenu:React.FC<OwnProps> = ({name, price, category, showBestMenuName}) => {
    return (
        <div>{name}</div>
    )
}
export default BestMenu;
import React from "react";
import { Restaurant,Address } from "./model/restaurant";

interface OwnProps{
    info:Restaurant,
    changeAddress(address:Address):void,
}

const Store:React.FC<OwnProps> = ({info})=>{
    return(
        <div>
            {info.name}
        </div>
    )
}

export default Store;

 

타입 모델 : restaurant.ts

// let data ={
//     name : '누나네 식당',
//     category:'western',
//     address:{
//       city:'incheoi',
//       detail:'somewhere',
//       zipCode:23425634
//     },
//     menu:[
//       {
//         name:"rose pasta",
//         price : 2000,
//         category:"PASTA"
//       },
//       {
//         name:"garlic steak",
//         price : 3000,
//         category:"STEAK"
//       }
//     ]
//   }
export type Restaurant = {

	name:string;
    category:string;
    address:Address;
    menu:Menu[];
}

export type Address ={
    city:string;
    detail:string;
    zipCode:Number;
}

export type Menu={
    	name:string;
        price:number;
        category:string;
}

export type AddressWithoutZip = Omit<Address,'zipCode'>
export type RestaurantOnlyCategory = Pick<Restaurant,'category'>


//Type이 무엇인지 모를 때..
export type ApiResponse<T>={
    data:T[],
    totalPage:number,
    page:number
}

export type RestaurantResponse =  ApiResponse<Restaurant>
export type MenuResponse =  ApiResponse<Menu>

짧게 보는 개발의 변천

  • 브라우저에서 작동하는 스크립트 언어로 자바스크립 등장(by 넷스케이프)
  • 마이크로소프트도 익스플로러 탑재 JScript
  • 호환 문제 발생 / ECMA 표준화 단체에서 자바스크립트 표준 제작 
  • Ajax를 활용한 인터랙티브한 애플리케이션 등장(지메일 등)
  • Ajax 이후 기존보다 많은 기능을 가진 애플리케이션 RIA 클라이언트 사이드 구현으로 Ajax, DOM 조작 요구 발생
  • 각 벤더의 브라우저의 차이로 인해 제이쿼리 유행 시작
  • SPA의 인기 
고성능 애플리케이션 제공
서버 사이드, 프런트엔드 분업 쉬움
JSON API 통해 느슨한 결합의 설계
IOS나 안드로이드 등 네이티브 애플리케이션 클라이언트에 대해서도 AIP 통한 느슨한 결합의 시스템을 구성해 대응할 수 있음.

 

 


참고사이트:

https://www.codenary.co.kr/company/list

 

유명 IT 기업들의 기술 스택을 알아보세요 | 코드너리

코드너리에서 국내 100개가 넘는 스타트업들의 기술 스택 정보를 확인해보세요.

www.codenary.co.kr

https://www.typescriptlang.org/

 

JavaScript With Syntax For Types.

TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code.

www.typescriptlang.org

https://www.samsungsds.com/kr/insights/typescript.html

 

활용도가 높아지는 웹 프론트엔드 언어, 타입스크립트[TypeScript] | 인사이트리포트 | 삼성SDS

2012년 마이크로소프트가 발표한 타입스크립트(TypeScript)는 자바스크립트(JavaScript)를 기반으로 정적 타입 문법을 추가한 프로그래밍 언어입니다. 요즘은 대형 SI 프로젝트에서 흔하게 사용되고 있

www.samsungsds.com

https://codingapple.com/unit/typescript-tsconfig-json/

 

Typescript 컴파일시 세부설정 (tsconfig.json) - 코딩애플 온라인 강좌

tsconfig 파일 생성하기 여러분 프로젝트 폴더에  tsconfig.json 이라는 파일을 하나 생성합시다. 여기엔 타입스크립트 ts 파일들을 .js 파일로 변환할 때 어떻게 변환할 것인지 세부설정이 가능합니다

codingapple.com

https://www.youtube.com/watch?v=GHHUjITelsA

https://www.youtube.com/watch?v=xkpcNolC270

https://www.yes24.com/Product/Goods/119121955

 

타입스크립트, 리액트, Next.js로 배우는 실전 웹 애플리케이션 개발 - 예스24

TypeScript/React/Next.js로 실전적인 모던 웹 애플리케이션을 만들어 보자!《타입스크립트, 리액트, Next.js로 배우는 실전 웹 애플리케이션 개발》은 타입스크립트와 리액트, Next.js로 실무에서 사용하

www.yes24.com

https://chlolisher.tistory.com/131

 

클라이언트 사이드와 서버 사이드의 개념과 차이점 Client-side / Server-side

웹 프로그래밍에서 서버 사이드 / 클리아언트 사이드는 엄청난 의미를 가진다. 왜냐하면 어느쪽에 중심을 두느냐에 따라 프로젝트의 방향이 완전히 다르기때문이다. 1. 클라이언트 사이드(Client-

chlolisher.tistory.com

https://velog.io/@cheal3/%EC%84%9C%EB%B2%84%EC%82%AC%EC%9D%B4%EB%93%9C-%EB%A0%8C%EB%8D%94%EB%A7%81-SSR-%EA%B3%BC-%ED%81%B4%EB%9D%BC%EC%9D%B4%EC%96%B8%ED%8A%B8-%EC%82%AC%EC%9D%B4%EB%93%9C-%EB%A0%8C%EB%8D%94%EB%A7%81-CSR-%EC%97%90-%EB%8C%80%ED%95%B4

 

서버사이드 렌더링 (SSR) 과 클라이언트 사이드 렌더링 (CSR) 에 대해

기본적으로 웹은 클라이언트와 서버로 나누어진다. 클라이언트는 요청을 보내고 서버는 그 요청을 보고 특정 정보를 응답해 주고 , 클라이언트 측에서는 서버로부터 응답받은 html 문서를 보고 D

velog.io

https://tech.weperson.com/wedev/frontend/csr-ssr-spa-mpa-pwa/#ssr-server-side-rendering

 

CSR/SSR, SPA/MPA, PWA | 위펄슨 기술 블로그

CSR/SSR, SPA/MPA, PWA 이번 주제는 렌더링(Rendering)방식과 웹아키텍처(Architecture)에 관한 얘기입니다. 렌더링/웹아키텍처라는 말보다는 SSR, SPA등 용어를 주로 사용하므로 주제에 용어를 나열 하였습니

tech.weperson.com

프로그레시브 웹 애플리케이션 설명1

 

프로그레시브 웹 애플리케이션 설명2

https://fmontes.com/blog/difference-between-reactjs-and-nextjs

 

Difference between Reactjs and Nextjs

In short, React is a library, and NexJS is a framework, but do you know the difference between each?

fmontes.com

리액트 / next.js

 

react vs next.js - Google 검색

Next.js vs React: What are... www.imaginarycloud.com

www.google.com

https://www.youtube.com/watch?v=V9XLst8UEtk

반응형