Skip to content

React Project Structure

Overview

This chapter will deeply analyze the complete structure of React projects, including the role of each file and directory, the meaning of configuration files, the build process, and the working principles of the development environment. Understanding these will help you better manage and optimize React projects.

📁 Project Directory Structure

Create React App Project Structure

my-react-app/
├── public/                     # Static assets directory
│   ├── index.html             # HTML template file
│   ├── favicon.ico            # Website icon
│   ├── logo192.png            # PWA app icon
│   ├── logo512.png            # PWA app icon
│   ├── manifest.json          # PWA app manifest
│   └── robots.txt             # Search engine crawler configuration
├── src/                       # Source code directory
│   ├── components/            # Components directory (custom)
│   ├── hooks/                 # Custom Hooks (custom)
│   ├── utils/                 # Utility functions (custom)
│   ├── styles/                # Style files (custom)
│   ├── App.js                 # Main application component
│   ├── App.css                # Application styles
│   ├── App.test.js            # Application test
│   ├── index.js               # Application entry
│   ├── index.css              # Global styles
│   ├── logo.svg               # React Logo
│   └── reportWebVitals.js     # Performance monitoring
├── node_modules/              # Dependencies directory
├── package.json               # Project configuration
├── package-lock.json          # Dependencies lock file
├── README.md                  # Project documentation
└── .gitignore                 # Git ignore file

Vite Project Structure

my-vite-app/
├── public/                    # Static assets directory
│   └── vite.svg              # Vite Logo
├── src/                      # Source code directory
│   ├── assets/               # Asset files
│   │   └── react.svg         # React Logo
│   ├── App.jsx               # Main application component
│   ├── App.css               # Application styles
│   ├── index.css             # Global styles
│   └── main.jsx              # Application entry
├── index.html                # HTML template
├── package.json              # Project configuration
├── vite.config.js            # Vite configuration
└── README.md                 # Project documentation

📄 Core File Details

1. package.json - Project Configuration File

json
{
  "name": "my-react-app",           // Project name
  "version": "0.1.0",               // Project version
  "private": true,                  // Private project, prevents accidental publishing
  "dependencies": {                 // Production dependencies
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",             // React core library
    "react-dom": "^18.2.0",         // React DOM renderer
    "react-scripts": "5.0.1",       // Build scripts
    "web-vitals": "^2.1.4"          // Performance monitoring
  },
  "scripts": {                      // Executable scripts
    "start": "react-scripts start",       // Start development server
    "build": "react-scripts build",       // Build production version
    "test": "react-scripts test",         // Run tests
    "eject": "react-scripts eject"        // Expose configuration (irreversible)
  },
  "eslintConfig": {                 // ESLint configuration
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {                 // Browser compatibility
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

2. public/index.html - HTML Template

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <!-- Website icon, %PUBLIC_URL% will be replaced with the public directory path -->
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

    <!-- Mobile adaptation -->
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Theme color, used for browser UI -->
    <meta name="theme-color" content="#000000" />

    <!-- Website description, used for SEO -->
    <meta name="description" content="Web app created using Create React App" />

    <!-- PWA app icon -->
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <!-- PWA manifest file -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <!--
      Note:
      1. %PUBLIC_URL% will be replaced during build
      2. Only files in the public directory can be referenced
      3. It is recommended to place meta tags in the head
    -->

    <title>My React App</title>
  </head>
  <body>
    <!-- Message shown when JavaScript is not supported -->
    <noscript>You need to enable JavaScript to run this app.</noscript>

    <!-- Mount point for React app -->
    <div id="root"></div>

    <!--
      React app will be injected into the root element
      Build后的 JavaScript 和 CSS files will be automatically inserted here
    -->
  </body>
</html>

3. src/index.js - Application Entry Point

jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';              // Global styles
import App from './App';           // Main application component
import reportWebVitals from './reportWebVitals';  // Performance monitoring

// Create React root node (React 18 new API)
const root = ReactDOM.createRoot(document.getElementById('root'));

// Render app to root node
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// Performance monitoring (optional)
// If you want to start measuring performance, pass a function
// to log results (e.g., reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

// React.StrictMode helps you:
// 1. Identify unsafe lifecycle methods
// 2. Warn about usage of deprecated string ref API
// 3. Warn about usage of deprecated findDOMNode method
// 4. Detect unexpected side effects
// 5. Detect outdated context API
// 6. Ensure reusable state

4. src/App.js - Main Application Component

jsx
import React from 'react';
import './App.css';

// Main application component - root component of the app
function App() {
  return (
    <div className="App">
      {/* Application header */}
      <header className="App-header">
        <img src="/logo192.png" className="App-logo" alt="logo" />
        <h1>Welcome to React</h1>
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

// Component naming conventions:
// 1. Component names must start with an uppercase letter (PascalCase)
// 2. File names are usually the same as component names
// 3. Use descriptive names

🛠️ Configuration File Details

1. .gitignore - Git Ignore File

gitignore
# Dependencies directory
/node_modules
/.pnp
.pnp.js

# Test coverage
/coverage

# Production build
/build

# Environment variables
.env.local
.env.development.local
.env.test.local
.env.production.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# IDE files
.vscode/
.idea/
*.swp
*.swo

# Operating system files
.DS_Store
Thumbs.db

2. public/manifest.json - PWA Manifest

json
{
  "short_name": "React App",        // App short name
  "name": "Create React App Sample", // App full name
  "icons": [                        // App icons
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",                 // Start URL
  "display": "standalone",          // Display mode
  "theme_color": "#000000",         // Theme color
  "background_color": "#ffffff"     // Background color
}

3. public/robots.txt - Search Engine Configuration

# https://www.robotstxt.org/robotstxt.html
User-agent: *           # For all search engines
Disallow:              # Allow crawling all pages

# If you want to disallow certain paths:
# Disallow: /admin/
# Disallow: /private/

📦 Dependencies Explanation

Core Dependencies

javascript
// React core package
"react": "^18.2.0"              // React core library
"react-dom": "^18.2.0"          // DOM renderer

// Build tools
"react-scripts": "5.0.1"        // Build and development scripts

// Testing tools
"@testing-library/react": "^13.3.0"     // React testing tools
"@testing-library/jest-dom": "^5.16.4"  // Jest DOM assertions
"@testing-library/user-event": "^13.5.0" // User event simulation

// Performance monitoring
"web-vitals": "^2.1.4"          // Web performance metrics

Common Optional Dependencies

bash
# Routing
npm install react-router-dom

# State management
npm install redux react-redux @reduxjs/toolkit
npm install zustand

# UI component libraries
npm install antd
npm install @mui/material @emotion/react @emotion/styled

# Styling
npm install styled-components
npm install sass

# Utility libraries
npm install lodash
npm install axios
npm install date-fns

# Form handling
npm install react-hook-form
npm install formik yup

# Animation
npm install framer-motion
npm install react-spring

🚀 Build Process Analysis

Development Mode (npm start)

javascript
// Development mode features:
// 1. Hot Reload
// 2. Source Maps
// 3. Error Overlay
// 4. Auto-refresh browser

// Development server configuration (internal)
const config = {
  mode: 'development',
  devtool: 'cheap-module-source-map',
  devServer: {
    hot: true,                    // Enable hot reload
    historyApiFallback: true,     // SPA routing support
    compress: true,               // Enable gzip compression
    port: 3000,                   // Port number
    open: true                    // Auto open browser
  }
}

Production Build (npm run build)

javascript
// Production build features:
// 1. Code Minification
// 2. Tree Shaking
// 3. Code Splitting
// 4. Asset Optimization

// Build output structure
build/
├── static/
│   ├── css/
│   │   ├── main.[hash].css      // Minified CSS
│   │   └── main.[hash].css.map  // CSS source map
│   ├── js/
│   │   ├── main.[hash].js       // Main application code
│   │   ├── main.[hash].js.map   // JS source map
│   │   └── [number].[hash].js   // Code splitting chunks
│   └── media/
│       └── logo.[hash].svg      // Static assets
├── index.html                   // HTML file
├── asset-manifest.json          // Asset manifest
└── manifest.json               // PWA manifest

🔧 Environment Variable Configuration

Environment Variable Files

bash
# .env - All environments
REACT_APP_API_URL=https://api.example.com
REACT_APP_APP_NAME=My React App

# .env.local - Local environment (git ignored)
REACT_APP_API_KEY=your-secret-api-key

# .env.development - Development environment
REACT_APP_DEBUG=true
REACT_APP_API_URL=http://localhost:3001

# .env.production - Production environment
REACT_APP_DEBUG=false
REACT_APP_API_URL=https://api.production.com

Using Environment Variables

jsx
// Using in React components
function App() {
  const apiUrl = process.env.REACT_APP_API_URL;
  const appName = process.env.REACT_APP_APP_NAME;
  const isDebug = process.env.REACT_APP_DEBUG === 'true';

  console.log('API URL:', apiUrl);
  console.log('App Name:', appName);
  console.log('Debug Mode:', isDebug);

  return (
    <div>
      <h1>{appName}</h1>
      {isDebug && <div>Debug mode enabled</div>}
    </div>
  );
}

// Note:
// 1. Environment variables must start with REACT_APP_
// 2. Environment variables are replaced with strings during build
// 3. Do not store sensitive information in environment variables

📊 Project Structure Best Practices

src/
├── components/              # Reusable components
│   ├── common/             # Common components
│   │   ├── Button/
│   │   │   ├── Button.jsx
│   │   │   ├── Button.module.css
│   │   │   └── index.js
│   │   └── Modal/
│   └── layout/             # Layout components
│       ├── Header/
│       ├── Footer/
│       └── Sidebar/
├── pages/                  # Page components
│   ├── Home/
│   ├── About/
│   └── Contact/
├── hooks/                  # Custom Hooks
│   ├── useAuth.js
│   ├── useApi.js
│   └── useLocalStorage.js
├── services/               # API services
│   ├── api.js
│   ├── auth.js
│   └── config.js
├── utils/                  # Utility functions
│   ├── helpers.js
│   ├── constants.js
│   └── formatters.js
├── styles/                 # Style files
│   ├── globals.css
│   ├── variables.css
│   └── mixins.css
├── assets/                 # Static assets
│   ├── images/
│   ├── icons/
│   └── fonts/
└── store/                  # State management
    ├── index.js
    ├── authSlice.js
    └── userSlice.js

Component File Structure

Button/
├── Button.jsx              # Component main file
├── Button.module.css       # Style file
├── Button.test.js          # Test file
├── Button.stories.js       # Storybook story
└── index.js               # Export file

// index.js content
export { default } from './Button';
export * from './Button';

File Naming Conventions

javascript
// Component files: PascalCase
Button.jsx
UserProfile.jsx
NavigationBar.jsx

// Utility files: camelCase
authHelpers.js
dateUtils.js
apiConfig.js

// Constant files: UPPERCASE or camelCase
constants.js
API_ENDPOINTS.js

// Style files: kebab-case or camelCase
button.module.css
user-profile.css

🔍 Debugging and Development Tools

Browser Developer Tools

jsx
// Using console for debugging
function MyComponent({ data }) {
  console.log('Component rendering', { data });
  console.table(data);                    // Display in table format
  console.time('Rendering time');         // Start timing

  const result = processData(data);

  console.timeEnd('Rendering time');      // End timing
  console.warn('This is a warning');      // Warning message
  console.error('This is an error');      // Error message

  return <div>{result}</div>;
}

React Developer Tools

jsx
// Component displayName setting
function MyComponent() {
  return <div>My Component</div>;
}
MyComponent.displayName = 'MyComponent';

// Using React Profiler
import { Profiler } from 'react';

function onRenderCallback(id, phase, actualDuration, baseDuration, startTime, commitTime) {
  console.log('Profiler:', {
    id,              // Component ID
    phase,           // mount or update
    actualDuration,  // Actual render time
    baseDuration,    // Estimated render time
    startTime,       // Start render time
    commitTime       // Commit time
  });
}

function App() {
  return (
    <Profiler id="App" onRender={onRenderCallback}>
      <MyComponent />
    </Profiler>
  );
}

📝 Chapter Summary

Through this chapter, you should have mastered:

Project Structure Understanding

  • ✅ The role of each file and directory
  • ✅ The meaning and usage of configuration files
  • ✅ Build process and optimization mechanisms
  • ✅ Configuration and usage of environment variables

Best Practices

  • ✅ Reasonable directory structure organization
  • ✅ File naming conventions
  • ✅ Component structure design
  • ✅ Development tool usage

Development Skills

  • ✅ Project configuration management
  • ✅ Dependency package management
  • ✅ Debugging techniques
  • ✅ Performance monitoring

Core Concepts

  1. Modular Development: Separation of components, tools, and styles
  2. Build Optimization: Code splitting, compression, caching
  3. Development Experience: Hot reload, error hints, debugging tools
  4. Project Management: Dependency management, version control, environment configuration

Continue Learning: Next Chapter - React Element Rendering

Content is for learning and research only.