create-react-app项目中index.html未加script标签为何能渲染index.tsx?
关于Create React App自动渲染入口文件的疑问与解答
问题背景
使用Create React App创建的项目中,public/index.html内容如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/juno-icon.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@700&display=swap" rel="stylesheet" /> <title>Issue Report</title> </head> <body> <div id="root"></div> </body> </html>
该文件未手动添加任何script标签,却能自动渲染src/index.tsx的内容,src/index.tsx代码如下:
import React from 'react'; import ReactDOM from 'react-dom/client'; import reportWebVitals from './reportWebVitals'; import App from './popup/components/App'; import './popup/styles/index.css'; import { BrowserRouter } from 'react-router-dom'; import { QueryClientProvider, QueryClient } from 'react-query'; import { ReactQueryDevtools } from 'react-query/devtools' const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, }, }, }) root.render( <QueryClientProvider client={queryClient}> <BrowserRouter> <React.StrictMode> <App /> </React.StrictMode> </BrowserRouter> <ReactQueryDevtools initialIsOpen={true} position='bottom-right' /> </QueryClientProvider> ); reportWebVitals();
疑问点:这种自动渲染的机制是如何运作的?CRA是怎么确定要渲染的文件的?
解答
这是因为Create React App(简称CRA)已经封装好了底层构建工具的配置,核心逻辑基于webpack:
- 内置入口约定:CRA预设
src/index.tsx(JS项目为src/index.js)作为项目唯一入口文件,无需手动配置。webpack会从这个入口开始,递归打包所有依赖的模块(包括组件、样式、第三方库等)。 - 自动注入script标签:运行
npm start启动开发服务器,或npm run build构建生产包时,webpack会自动将打包后的JS文件(开发环境为bundle.js,生产环境是带哈希值的文件名)以<script>标签形式注入到public/index.html的<body>末尾。你可以打开浏览器开发者工具的「元素」面板,直接看到这个自动添加的标签。 - 渲染关联逻辑:
src/index.tsx里的代码通过document.getElementById('root')定位到public/index.html中的<div id="root">元素,再调用root.render()将React组件树挂载到这个容器里,完成页面渲染。
简单来说,CRA把webpack的复杂配置全部隐藏,只要遵循它的文件结构约定,就能自动完成打包、注入和渲染的全流程。
内容的提问来源于stack exchange,提问作者dani_l_n
相关产品推荐
相关产品推荐

