프런트엔드 프로젝트 구성요소 폴더 구성
폴더 구조 프론트엔드 프로젝트의 구성요소는 중요합니다. 프로젝트를 더 쉽게 개발하고 유지 관리할 수 있기 때문입니다. 특히 크거나 복잡한 구성 요소를 처리할 때 폴더를 구성하면 코드를 체계적으로 정리하고 쉽게 찾고 이해할 수 있습니다.
폴더 구조는 이렇습니다. 다양한 형식의 구성요소 다음을 사용하여 개발된 프로젝트에서 일반적으로 사용됩니다. Next.js 및 TypeScript:
1. 원자적 디자인 구조
Atomic Design은 구성 요소를 복잡성과 기능에 따라 구분하는 디자인 개념입니다. 원자, 분자, 유기체, 템플릿, 페이지의 5가지 레벨로 구분됩니다.
src/ └── components/ ├── atoms/ # Small, reusable elements (e.g., buttons, inputs) │ ├── Button.tsx │ ├── Input.tsx │ ├── Icon.tsx │ └── ... # Additional atoms │ ├── molecules/ # Combinations of atoms (e.g., form groups) │ ├── FormInput.tsx │ ├── NavLink.tsx │ └── ... # Additional molecules │ ├── organisms/ # Complex UI components (e.g., headers, cards) │ ├── Header.tsx │ ├── Card.tsx │ ├── Footer.tsx │ └── ... # Additional organisms │ ├── templates/ # Page templates (layouts with placeholders) │ ├── MainLayout.tsx │ ├── DashboardLayout.tsx │ └── ... # Additional templates │ └── pages/ # Page-specific components (used directly in pages) ├── HomePage.tsx ├── AboutPage.tsx └── ... # Additional page components
예:
원자: Button.tsx
import React from 'react'; interface ButtonProps { label: string; onClick: () => void; type?: 'button' | 'submit' | 'reset'; disabled?: boolean; } const Button: React.FC<ButtonProps> = ({ label, onClick, type = 'button', disabled = false }) => ( <button type={type} onClick={onClick} disabled={disabled} className="btn"> {label} </button> ); export default Button;
분자: FormInput.tsx
import React from 'react'; import Input from '../atoms/Input'; import Label from '../atoms/Label'; interface FormInputProps { label: string; value: string; onChange: (value: string) => void; } const FormInput: React.FC<FormInputProps> = ({ label, value, onChange }) => ( <div className="form-input"> <Label text={label} /> <Input value={value} onChange={onChange} /> </div> ); export default FormInput;
유기체: Header.tsx
import React from 'react'; import NavLink from '../molecules/NavLink'; import Logo from '../atoms/Logo'; const Header: React.FC = () => ( <header className="header"> <Logo /> <nav> <NavLink href="/" label="Home" /> <NavLink href="/about" label="About" /> <NavLink href="/contact" label="Contact" /> </nav> </header> ); export default Header;
2. 기능 기반 구조
기능이나 모듈별로 구성 요소를 분리하는 구조는 기능이 풍부한 프로젝트에서 널리 사용됩니다. 기능을 효율적으로 관리하고 확장하는 데 도움이 됩니다
src/ └── components/ ├── authentication/ # Components related to authentication │ ├── Login.tsx │ ├── Signup.tsx │ └── PasswordReset.tsx │ ├── dashboard/ # Components specific to the dashboard │ ├── DashboardHeader.tsx │ ├── DashboardSidebar.tsx │ └── StatsCard.tsx │ ├── userProfile/ # Components for user profile │ ├── ProfileHeader.tsx │ ├── EditProfileForm.tsx │ └── Avatar.tsx │ ├── shared/ # Shared or common components across features │ ├── Button.tsx │ ├── Modal.tsx │ └── ... # Additional shared components │ └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Sidebar.tsx
예:
인증: Login.tsx
import React, { useState } from 'react'; import Button from '../shared/Button'; import FormInput from '../shared/FormInput'; const Login: React.FC = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleLogin = () => { // Logic for login }; return ( <div className="login"> <h2>Login</h2> <FormInput label="Email" value={email} onChange={setEmail} /> <FormInput label="Password" value={password} onChange={setPassword} /> <Button label="Login" onClick={handleLogin} /> </div> ); }; export default Login;
대시보드: StatsCard.tsx
import React from 'react'; interface StatsCardProps { title: string; value: number; icon: React.ReactNode; } const StatsCard: React.FC<StatsCardProps> = ({ title, value, icon }) => ( <div className="stats-card"> <div className="stats-card-icon">{icon}</div> <div className="stats-card-info"> <h3>{title}</h3> <p>{value}</p> </div> </div> ); export default StatsCard;
3. 도메인 중심 구조
이 구조는 프로젝트의 도메인이나 제한된 컨텍스트에 따라 구성 요소를 구성하는 데 중점을 둡니다. 따라서 이 구조는 명확한 도메인 분리가 필요한 복잡한 시스템에 적합합니다
src/ └── components/ ├── domain/ │ ├── product/ # Components related to product domain │ │ ├── ProductCard.tsx │ │ ├── ProductList.tsx │ │ └── ProductDetail.tsx │ │ │ ├── cart/ # Components for cart domain │ │ ├── CartItem.tsx │ │ ├── CartSummary.tsx │ │ └── CartIcon.tsx │ │ │ ├── user/ # Components for user domain │ │ ├── UserAvatar.tsx │ │ ├── UserProfile.tsx │ │ └── UserSettings.tsx │ │ │ └── ... # Additional domain-specific components │ ├── ui/ # UI elements (atoms, molecules, etc.) │ ├── atoms/ │ ├── molecules/ │ └── organisms/ │ └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Sidebar.tsx
예:
제품: ProductCard.tsx
import React from 'react'; interface ProductCardProps { name: string; price: number; imageUrl: string; onAddToCart: () => void; } const ProductCard: React.FC<ProductCardProps> = ({ name, price, imageUrl, onAddToCart }) => ( <div className="product-card"> <img src={imageUrl} alt={name} className="product-card-image" /> <div className="product-card-info"> <h3>{name}</h3> <p>${price.toFixed(2)}</p> <button onClick={onAddToCart}>Add to Cart</button> </div> </div> ); export default ProductCard;
카트: CartSummary.tsx
import React from 'react'; interface CartSummaryProps { totalItems: number; totalPrice: number; } const CartSummary: React.FC<CartSummary Props> = ({ totalItems, totalPrice }) => ( <div className="cart-summary"> <h3>Cart Summary</h3> <p>Total Items: {totalItems}</p> <p>Total Price: ${totalPrice.toFixed(2)}</p> <button>Checkout</button> </div> ); export default CartSummary;
4. 스토리북을 활용한 CDD(컴포넌트 중심 개발)
이 구조는 크로스 플랫폼 개발을 지원하도록 설계되었습니다. 컴포넌트 중심 개발(CDD) 메인 애플리케이션과 별도의 형식으로 컴포넌트를 개발하고 테스트할 수 있는 스토리북을 사용
src/ └── components/ ├── Button/ │ ├── Button.tsx # Component implementation │ ├── Button.stories.tsx # Storybook stories │ ├── Button.test.tsx # Unit tests │ └── Button.module.css # Component-specific styles │ ├── Input/ │ ├── Input.tsx │ ├── Input.stories.tsx │ ├── Input.test.tsx │ └── Input.module.css │ ├── Modal/ │ ├── Modal.tsx │ ├── Modal.stories.tsx │ ├── Modal.test.tsx │ └── Modal.module.css │ └── ... # Additional component folders
예:
버튼: Button.tsx
import React from 'react'; import styles from './Button.module.css'; interface ButtonProps { label: string; onClick: () => void; variant?: 'primary' | 'secondary'; } const Button: React.FC<ButtonProps> = ({ label, onClick, variant = 'primary' }) => ( <button className={`${styles.btn} ${styles[variant]}`} onClick={onClick}> {label} </button> ); export default Button;
버튼: Button.stories.tsx (스토리북)
import React from 'react'; import { Meta, Story } from '@storybook/react'; import Button, { ButtonProps } from './Button'; export default { title: 'Components/Button', component: Button, } as Meta; const Template: Story<ButtonProps> = (args) => <Button {...args} />; export const Primary = Template.bind({}); Primary.args = { label: 'Primary Button', onClick: () => console.log('Primary Button Clicked'), variant: 'primary', }; export const Secondary = Template.bind({}); Secondary.args = { label: 'Secondary Button', onClick: () => console.log('Secondary Button Clicked'), variant: 'secondary', };
5. 공유 구성요소 라이브러리
여러 팀이 함께 작업하는 프로젝트에서 공통 구성 요소를 사용하는 구조를 만드는 것이 중요합니다. 이 구조는 프로젝트 전반에 걸쳐 재사용할 수 있는 구성 요소를 분리하는 것을 강조합니다
src/ └── components/ ├── shared/ # Shared components across the application │ ├── Button/ │ │ ├── Button.tsx │ │ └── Button.module.css │ │ │ ├── Modal/ │ │ ├── Modal.tsx │ │ └── Modal.module.css │ │ │ └── ... # Additional shared components │ ├── featureSpecific/ # Feature-specific components │ ├── UserProfile/ │ │ ├── ProfileHeader.tsx │ │ ├── ProfileDetails.tsx │ │ └── Avatar.tsx │ │ │ ├── ProductList/ │ │ ├── ProductCard.tsx │ │ └── ProductFilter.tsx │ │ │ └── ... # Additional feature-specific components │ └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Sidebar.tsx
ตัวอย่าง:
Shared: Modal.tsx
import React from 'react'; import styles from './Modal.module.css'; interface ModalProps { title: string; isOpen: boolean; onClose: () => void; } const Modal: React.FC<ModalProps> = ({ title, isOpen, onClose, children }) => { if (!isOpen) return null; return ( <div className={styles.modalOverlay}> <div className={styles.modal}> <h2>{title}</h2> <button className={styles.closeButton} onClick={onClose}> × </button> <div className={styles.modalContent}>{children}</div> </div> </div> ); }; export default Modal;
Feature-Specific: ProfileHeader.tsx
import React from 'react'; interface ProfileHeaderProps { name: string; bio: string; avatarUrl: string; } const ProfileHeader: React.FC<ProfileHeaderProps> = ({ name, bio, avatarUrl }) => ( <div className="profile-header"> <img src={avatarUrl} alt={name} className="profile-avatar" /> <h1>{name}</h1> <p>{bio}</p> </div> ); export default ProfileHeader;
Factors to Consider When Structuring Components
- Reusability: ควรแยก component ที่สามารถใช้ซ้ำได้ออกจาก component ที่เฉพาะเจาะจงกับฟีเจอร์
- Maintainability: การจัดโครงสร้างที่ดีช่วยให้การดูแลรักษาและการอัพเดตโปรเจคเป็นไปอย่างราบรื่น
- Scalability: โครงสร้างที่ดีจะช่วยให้การขยายฟีเจอร์และการเพิ่ม component ใหม่ ๆ เป็นเรื่องง่าย
- Performance: ใช้เทคนิคที่เหมาะสมในการโหลดและใช้ component เพื่อให้แน่ใจว่าแอปพลิเคชันของคุณมีประสิทธิภาพ
Best Practices for Component Structure
- Single Responsibility Principle: แต่ละ component ควรทำหน้าที่เดียวและทำได้ดี
- Component Naming: ตั้งชื่อ component ให้สื่อความหมายและชัดเจน
- Component Composition: ใช้ composition แทน inheritance เมื่อสร้าง component ใหม่
- Use Prop Types or TypeScript: กำหนด prop types หรือใช้ TypeScript interfaces เพื่อเพิ่มความปลอดภัยในการใช้งาน
- Write Tests: เขียน unit tests สำหรับ component ทุกตัวเพื่อตรวจสอบการทำงาน
ด้วยข้อมูลและแนวทางเหล่านี้ หวังว่าคุณจะสามารถจัดโครงสร้างในโฟลเดอร์ components ของโปรเจคได้อย่างมีประสิทธิภาพและเหมาะสมกับความต้องการของโปรเจคของคุณ!
위 내용은 프런트엔드 프로젝트 구성요소 폴더 구성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

zustand 비동기 작업의 데이터 업데이트 문제. Zustand State Management Library를 사용할 때는 종종 비동기 작업이시기 적절하게 발생하는 데이터 업데이트 문제가 발생합니다. � ...
