happhee.github.io's Introduction
happhee.github.io's People
happhee.github.io's Issues
이미지
지난 10/26에 Next.js 13버전을 발표했다.
이 글을 통해 어떤 부분이 달라졌고, 내가 배포한 nori 에서 변경해야 할 부분을 먼저 점검해보고자 한다.
공식문서를 참고하였다.
👇 최신 버전을 다운로드 하고자 하면 아래의 명령을 수행하면 된다.
npm i next@latest react@latest react-dom@latest eslint-config-next@latest
✨ app/ Directory (beta)
Next.js에서 가장 사랑받는 기능 중 하나는 파일 시스템 라우터이다. 즉, 폴더 안에 파일을 옮겨놓기만 애플리케이션에서 즉시 경로를 생성할 수 있다.
위의 폴더 구조를 따르게 되면 https://www.with-nori.com/write, https://www.with-nori.com/comunity로 경로가 생성된다.
👇 일단, app/ 의 구조로 바꾸기 위해서는 next.config.js를 수정해주어야 한다.
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
// 추가
experimental: { appDir: true },
};
module.exports = nextConfig;
✨ Layouts
하지만 이제는 pages가 아닌 app에 page와 layout을 넣어주어야 한다.
//app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
);
}
// app/page.tsx
export default function page() {
return <div>메인 페이지 입니다</div>;
}
해당 페이지와 레이아웃을 적용한 결과이다.
여기서 RootLayout에 네비게이션바를 넣어주면..!
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<head></head>
<body>
<nav>네비게이션 바</nav>
{children}
</body>
</html>
);
}
아래처럼 네비게이션바가 defalut로 설정된 것을 확인할 수 있다💡
✨ Data Fetching
지금까지 next에서 SSR을 적용할 때는 getServerSideProps, getStaticProps를 사용하였다.import { GetServerSideProps } from "next";
export default function page() {
return <div>메인 페이지 입니다</div>;
}
export const getServerSideProps: GetServerSideProps = async (context) => {
const res = await fetch("https://dummyjson.com/todos/1");
const data = await res.json();
return {
props: {
data,
},
};
};
하지만, app에서는 해당 메소드를 지원하지 않는다는 것을 확인할 수 있다.
그렇다면 어떻게 데이터를 불러와야 할까?
import { use } from "react";
export default function page() {
const data = use(getData());
return (
<div>
메인 페이지 입니다<p>{data.todo}</p>
</div>
);
}
export const getData = async () => {
const res = await fetch("https://dummyjson.com/todos/1");
const data = await res.json();
return data;
};
위와 같이 getData라는 함수를 선언한 뒤에, use() 안에 넣어주기만 하면 요청이 이루어진다.
❗️❗️❗️여기서❗️❗️❗️
fetch 구문의 URL 뒤에 { cache: '' } 자리에 무엇이 들어가냐에 따라 기존의 getServerSideProps, getStaticProps와 유사한 기능을 구현하게 된다.
성공적으로 Data Fetching이 이루어진 것을 확인할 수 있다.✨ next/Image
👇Image 컴포넌트를 통해서 이미지 파일을 넣을 수 있는데,
<Image
src={`https://nori-image.s3.ap-northeast-2.amazonaws.com/${image}`}
></Image>
Next.js 13에서는 아래의 두 가지가 업데이트되었다.
- alt기본적으로 태그를 필요로 하는 접근성 향상
- 이미지 로드가 느릴 경우에 기존의 레이아웃이 밀려나는 현상인 Layout Shift를 막기위해 자동으로 width height를 설정하여 최적화
✨ next/font
👇font도 Image와 마찬가지로 Layout Shift를 막고, 이제 구글 폰트가 내장되어진것이 크게 달라졌다!
yarn add @next/font
폰트를 설치하고, 원하는 구글 폰트를 불러와 className으로 적용시키면 된다.
import { Roboto_Mono } from "@next/font/google";
const roboto = Roboto_Mono({
weight: "400",
});
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html className={roboto.className}>
<head></head>
<body>
<nav>네비게이션 바</nav>
{children}
</body>
</html>
);
}
아래처럼 글꼴이 바뀌어 진 것을 확인할 수 있다.
### ✨ next/link기존 Next.js 12에서는 태그 이후에 자식으로 반드시 태그를 필요로 하였다.
<Link href={`/write/${cid}`}>
<li>
<a>수정하기</a>
</li>
</Link>
하지만, Next.js 13에서는 항상 를 렌더링 하기에 자식으로 태그를 가질 필요가 없어졌다.
<Link href={`/write/${cid}`}>
<li>수정하기</li>
</Link>
🌈 글을 마치며
react-router-dom의 업데이트 만큼 많은 부분이 바뀐 것은 아니었지만, Link태그나 이미지와 app/으로 페이지 이동을 구현하는 것은 재미있게 살펴보았다. 다만, getServerSideProps, getStaticProps을 사용하지 않고, cache를 인자로 넣어주는 것이 SSR에 올바른 방벙인지에 대해서는 더 살펴봐야겠다는 생각이 들었다. 앞으로의 업데이트가 기대가 된다.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.