You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中public目录位置及外置原因咨询

Why does Create React App place the public/ folder outside src/?

Great question—this is one of those folder structure choices that feels arbitrary at first glance, but there are practical, intentional reasons behind CRA's default setup. Let's break it down:

1. Separation of "processed" vs. "static" assets

Everything inside src/ is meant to be processed by Webpack during your build:

  • JSX files get transpiled to vanilla JavaScript via Babel
  • CSS/SCSS gets minified, modularized, or injected into bundles
  • Images/fonts get optimized, hashed, and bundled where needed

The public/ folder, by contrast, holds assets that are copied directly to the build/ directory without any processing. Think things like:

  • Your favicon.ico or app icons
  • robots.txt or sitemap.xml for SEO
  • Third-party scripts you load via CDN (e.g., <script src="https://example.com/library.js"> in index.html)

2. Index.html is a template, not source code

You’re right that index.html is critical to your app—but it’s not part of your "source code" in the same way components or utility functions are. CRA uses it as a template for Webpack to inject your compiled bundles (like main.xyz.js) into.

If it lived inside src/, there’s a risk Webpack might try to process it (e.g., via html-loader) which isn’t what we want. Keeping it in public/ makes it clear this file is a static template, not something to be transpiled or bundled.

3. Clear project boundaries

This split helps enforce a mental model:

  • src/: The code you write, test, and maintain day-to-day. Everything here is part of your app’s logic.
  • public/: Static assets that support your app but don’t need to be part of the build pipeline. They’re often less frequently modified than your source code.

This makes onboarding new developers easier—they can quickly distinguish between core app code and supporting static files.

4. Avoiding accidental configuration headaches

CRA’s default Webpack setup is optimized to handle src/ and public/ differently. Putting public/ outside src/ prevents edge cases where Webpack might misinterpret static assets as part of your module graph, leading to unexpected build errors or bloated bundles.


To be clear, folder structure does have some subjectivity, but CRA’s choice is rooted in reducing configuration friction and establishing a consistent, community-accepted pattern. If you really need to adjust it, you could eject or use tools like customize-cra to modify the Webpack config—but the default setup works well for most React apps.

内容的提问来源于stack exchange,提问作者J Seabolt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:31:34