1. 코딩 스타일 가이드
이 문서는 Nextjs 프로젝트 개발 시 코딩 스타일 작성 방법을 설명합니다.
1
Componentization
가독성과 코드 재사용을 위해서 반드시 component화가 필요합니다. Composable commerce의 필수 요건이라 할 수 있습니다.
예시: layout.tsx
const Layout = ({ children }) => (
<div className="layout">
<header> Header content ... ... </header>
<main>{children}</main>
<footer> Footer content ... ... </footer>
</div>
);
export default Layout;이 파일 하나에 수 천 line 코딩하지 말고, Header와 Footer를 src/components/에 코딩 후 import 합니다.
import Header from '@/components/header';
import Footer from '@/components/footer';
const Layout = ({ children }) => (
<div className="layout">
<Header />
<main>{children}</main>
<Footer />
</div>
);
export default Layout;2
Nullish Coalescing
물음표 두 개 ??를 사용하는 문법입니다. ES2020에 도입된 JavaScript 문법이며, REST API의 response를 json으로 받아 체크할 때 유용합니다.
예시 설명:
false || true; // => true
false ?? true; // => false
false라는 값은 boolean 이고, 기본값 연산자 ??는 undefined 혹은 null 일 때만 뒤의 default 값을 사용합니다. 즉 응답 json에서 의도적인 빈 문자열 "" 값을 받을 때 이를 변형하지 않습니다.
사용 예시:
const name = foo ?? "default value";3
4
5
try-catch
예시:
async function fetchData() {
// An async function for fetching data from an API
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`API call failed with status: ${response.status}`);
}
return await response.json();
} catch (error) {
// Error handling or logging logic
throw error;
}
}7
마지막 업데이트