React项目中public目录位置及外置原因咨询
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.icoor app icons robots.txtorsitemap.xmlfor SEO- Third-party scripts you load via CDN (e.g.,
<script src="https://example.com/library.js">inindex.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

