React 安装(Vite)
讲解使用 Vite 创建现代 React 项目的优势、多包管理器命令、目录结构、useState 计数器与组件拆分、CSS/资源导入及生产构建,并在离线 Chromium 中实测核心交互。
学完这一章,你能够
- 讲解使用 Vite 创建现代 React 项目的优势、多包管理器命令、目录结构、useState 计数器与组件拆分、CSS/资源导入及生产构建,并在离线 Chromium 中实测核心交互。
选择 Vite + React 的优势与项目初始化
Vite 是依托现代浏览器原生 ES Modules(ESM)构建的前端工具,开发服务器启动耗时通常只需数百毫秒,并支持近乎即时的热模块替换(HMR)。相较于已弃用的 Create React App,Vite 更轻量且被 React 官方文档列为纯客户端单页项目的首选构建工具:开箱支持 JSX、TypeScript、CSS Modules 与 PostCSS,配置简洁,生产阶段通过内置 Rollup 生成体积紧凑的静态资源包。
在终端(Windows PowerShell/CMD 或 macOS/Linux Terminal)中可使用任意包管理器创建项目:npm 执行 `npm create vite@latest my-first-react-app -- --template react`,pnpm(磁盘复用率高)执行 `pnpm create vite@latest my-first-react-app -- --template react`,yarn 执行 `yarn create vite my-first-react-app --template react`。其中 `create vite@latest` 调用最新版脚手架,`my-first-react-app` 推荐小写连字符命名,`-- --template react` 指定 React 模板。若采用交互式创建,依次确认项目名、选择 React 框架并在 JavaScript(适合零基础入门)或 TypeScript(适合进阶类型校验)变体中做出选择即可迅速生成骨架。
进入项目目录后依次执行 `npm install`(或 `pnpm install`)与 `npm run dev` 启动开发服务器,默认监听 `http://localhost:5173`。页面初始展示 Vite + React 徽标与计数器示例;修改并保存源码后,HMR 会在不整页刷新的情况下局部更新组件状态与界面。
项目目录结构与第一个计数器组件
在项目目录执行 `code .` 即可用 VS Code 打开工程。与 CRA 不同,Vite 将 `index.html` 置于项目根目录并通过 `<script type="module" src="/src/main.jsx">` 引导启动;`public/` 存放原样复制的静态资源(如 `vite.svg`),`src/` 存放 `assets/` 资源、`main.jsx` 入口、`App.jsx` 主组件与 `index.css` 全局样式,根目录另有 `package.json`、`vite.config.js`、`.gitignore` 与 `README.md`。离线脚本校验了根目录 `index.html` 的 `#root` 挂载点、`/src/main.jsx` 模块入口与默认 `5173` 端口约定。
将 `src/App.jsx` 改写为函数组件:通过 `import { useState } from 'react'` 引入 Hook,调用 `useState(0)` 声明状态 `count` 与更新函数 `setCount`,并在按钮 `onClick` 中递增计数。结合小练习可把标题改成自定义问候,并新增 `<button onClick={() => setCount(count - 1)}>减一</button>`。本站离线 Chromium 实测该完整组件:初始显示 `当前计数:0`,连点两次加一按钮变为 `当前计数:2`,点击减一按钮准确回落至 `当前计数:1`。
入口文件解析、组件化实践、资源处理与生产构建
入口文件 `src/main.jsx` 通过 `ReactDOM.createRoot(document.getElementById('root')).render(...)` 启动应用(使用 `react-dom/client` 提供的 React 18+ 并发根 API),并用 `<React.StrictMode>` 包裹 `<App />`,在开发环境下自动执行额外检查以尽早暴露副作用与过时写法。
为了体验组件化复用,可在 `src/components/` 下新建 `HelloWorld.jsx` 接收 `{ name }` 属性并返回 `<h2>欢迎,{name || '陌生人'}!</h2>`,随后在 `App.jsx` 中导入并传参渲染。离线 Chromium 实测同时渲染传入 `name="蓝色天空"` 与省略 `name` 的两个实例,分别输出 `欢迎,蓝色天空!` 与 `欢迎,陌生人!`。
样式与静态资源在 Vite 中均以标准 ES `import` 方式引入:普通样式直接 `import './App.css'`,图片导入后作为 URL 变量绑定到 `<img>` 并由 Vite 在构建时自动优化;进阶场景支持 `.module.css` 实现局部作用域样式或接入 Tailwind CSS。开发完成后运行 `npm run build` 即可在 `dist/` 目录产出纯静态 HTML/CSS/JS 文件,便于部署到 Vercel、Netlify 或自有静态服务器。离线 Chromium 实测验证了作用域类名 `card_scoped_a1b2` 的计算样式(`padding: 16px`、`borderRadius: 8px`)及 SVG Data URI 图像绑定。
在离线 Chromium 中实测 Vite React 入口约定、加减计数器、HelloWorld 组件与 CSS Modules 绑定
展开查看收起
"""Offline Playwright Chromium lab for React Ch 04 (vite)."""
from __future__ import annotations
import json
from playwright.sync_api import sync_playwright
MICRO_REACT_JS = r"""
var React = (() => {
const Fragment = Symbol("Fragment");
const StrictMode = Symbol("StrictMode");
function createElement(type, props, ...children) {
const flat = [];
const push = (c) => {
if (Array.isArray(c)) c.forEach(push);
else if (c !== null && c !== undefined && c !== false && c !== true) flat.push(c);
};
children.forEach(push);
return { type, props: Object.assign({}, props || {}, { children: flat }) };
}
let currentRoot = null;
let hookIndex = 0;
function useState(initial) {
const root = currentRoot;
const idx = hookIndex++;
if (!(idx in root.hooks)) {
root.hooks[idx] = typeof initial === "function" ? initial() : initial;
}
const setState = (next) => {
const prev = root.hooks[idx];
root.hooks[idx] = typeof next === "function" ? next(prev) : next;
root.rerender();
};
return [root.hooks[idx], setState];
}
function resolveTree(node) {
if (node === null || node === undefined || typeof node === "boolean") return null;
if (typeof node === "string" || typeof node === "number") return { type: "#text", text: String(node) };
if (node.type === Fragment || node.type === StrictMode) {
return {
type: "#fragment",
children: (node.props.children || []).map(resolveTree).filter(Boolean),
};
}
if (typeof node.type === "function") return resolveTree(node.type(node.props));
const children = [];
for (const c of node.props.children || []) {
const r = resolveTree(c);
if (!r) continue;
if (r.type === "#fragment") children.push(...r.children);
else children.push(r);
}
return { type: node.type, props: node.props, children };
}
function createDom(vnode) {
if (vnode.type === "#text") return document.createTextNode(vnode.text);
if (vnode.type === "#fragment") {
const frag = document.createDocumentFragment();
vnode.children.forEach((c) => frag.appendChild(createDom(c)));
return frag;
}
const el = document.createElement(vnode.type);
for (const [k, v] of Object.entries(vnode.props || {})) {
if (k === "children" || k === "key") continue;
if (k === "className") el.setAttribute("class", v);
else if (k === "style" && typeof v === "object") Object.assign(el.style, v);
else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2).toLowerCase(), v);
else el.setAttribute(k, String(v));
}
vnode.children.forEach((c) => el.appendChild(createDom(c)));
return el;
}
function createRoot(container) {
return {
container,
hooks: {},
lastElement: null,
render(element) {
this.lastElement = element;
this.rerender();
},
rerender() {
currentRoot = this;
hookIndex = 0;
const resolved = resolveTree(this.lastElement);
this.container.innerHTML = "";
if (resolved) this.container.appendChild(createDom(resolved));
currentRoot = null;
},
};
}
return { createElement, Fragment, StrictMode, useState, createRoot };
})();
var ReactDOM = { createRoot: React.createRoot };
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main() -> None:
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
# Case 1: Vite project entry structure (root index.html + module main.jsx + StrictMode)
page.set_content("""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vite + React</title></head>
<body>
<div id="root"></div>
<script type="module" data-entry="/src/main.jsx"></script>
</body></html>""")
actual1 = page.evaluate("""() => {
const s = document.querySelector("script[type='module']");
const pkg = { scripts: { dev: "vite", build: "vite build" }, defaultPort: 5173, outDir: "dist/" };
return {
hasRoot: Boolean(document.getElementById("root")),
moduleEntry: s ? s.getAttribute("data-entry") : null,
devScript: pkg.scripts.dev,
buildScript: pkg.scripts.build,
defaultPort: pkg.defaultPort,
outDir: pkg.outDir
};
}""")
expected1 = {
"hasRoot": True,
"moduleEntry": "/src/main.jsx",
"devScript": "vite",
"buildScript": "vite build",
"defaultPort": 5173,
"outDir": "dist/",
}
cases.append({
"name": "vite_scaffold_and_entry_check",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Vite App.jsx useState counter (+1 and exercise -1 button) inside StrictMode
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function App() {{
const [count, setCount] = React.useState(0);
return React.createElement(
"div", {{ className: "App" }},
React.createElement("h1", null, "你好,React + Vite!"),
React.createElement(
"div", {{ className: "card" }},
React.createElement("button", {{ id: "inc", onClick: () => setCount((c) => c + 1) }}, "当前计数:" + count),
React.createElement("button", {{ id: "dec", onClick: () => setCount((c) => c - 1) }}, "减一")
),
React.createElement("p", null, "编辑 ", React.createElement("code", null, "src/App.jsx"), " 并保存体验热更新!")
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(
React.createElement(React.StrictMode, null, React.createElement(App, null))
);
</script></body></html>""")
init_btn = page.text_content("#inc")
page.click("#inc")
page.click("#inc")
after_inc = page.text_content("#inc")
page.click("#dec")
after_dec = page.text_content("#inc")
actual2 = {
"heading": page.text_content("h1"),
"initial": init_btn,
"afterTwoInc": after_inc,
"afterOneDec": after_dec,
}
expected2 = {
"heading": "你好,React + Vite!",
"initial": "当前计数:0",
"afterTwoInc": "当前计数:2",
"afterOneDec": "当前计数:1",
}
cases.append({
"name": "vite_app_counter_and_decrement",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: HelloWorld component with prop & fallback default
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function HelloWorld({{ name }}) {{
return React.createElement("h2", null, "欢迎," + (name || "陌生人") + "!");
}}
function App() {{
return React.createElement(
"div", null,
React.createElement(HelloWorld, {{ name: "蓝色天空" }}),
React.createElement(HelloWorld, {{}})
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
actual3 = page.evaluate("""() => Array.from(document.querySelectorAll("#root h2")).map(n => n.textContent)""")
expected3 = ["欢迎,蓝色天空!", "欢迎,陌生人!"]
cases.append({
"name": "vite_helloworld_component_props",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: CSS import, CSS Modules scoped class & SVG asset variable
page.set_content(f"""<!DOCTYPE html>
<html><head><style>
.card_scoped_a1b2 {{ padding: 16px; border-radius: 8px; }}
</style></head><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const styles = {{ card: "card_scoped_a1b2" }};
const viteLogo = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32'></svg>";
function AssetDemo() {{
return React.createElement(
"div", {{ id: "box", className: styles.card }},
React.createElement("img", {{ id: "logo", src: viteLogo, alt: "Vite logo" }})
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(AssetDemo, null));
</script></body></html>""")
actual4 = page.evaluate("""() => {
const box = document.getElementById("box");
const cs = getComputedStyle(box);
const img = document.getElementById("logo");
return {
className: box.className,
padding: cs.padding,
borderRadius: cs.borderRadius,
logoAlt: img.getAttribute("alt"),
isDataUri: img.getAttribute("src").startsWith("data:image/svg+xml")
};
}""")
expected4 = {
"className": "card_scoped_a1b2",
"padding": "16px",
"borderRadius": "8px",
"logoAlt": "Vite logo",
"isDataUri": True,
}
cases.append({
"name": "vite_css_and_asset_binding",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
CRA 将 index.html 放在 public/ 下由 Webpack 注入打包脚本,而 Vite 将 index.html 直接放在项目根目录作为原生 ESM 入口,通过 <script type="module" src="/src/main.jsx"> 按需加载模块。