React 安装(CDN)
介绍通过 UMD/CDN 脚本在单个 HTML 页面中体验 React 18 的配置方式、三大脚本职责、JSX 浏览器端转译开销与 ReactDOM.createRoot 挂载步骤。
学完这一章,你能够
- 介绍通过 UMD/CDN 脚本在单个 HTML 页面中体验 React 18 的配置方式、三大脚本职责、JSX 浏览器端转译开销与 ReactDOM.createRoot 挂载步骤。
CDN 引入方式与版本说明
除了本地脚手架之外,React 18.2.0 及之前提供 UMD 打包版本的发行版可以直接在普通 HTML 页面中通过 `<script>` 标签引入,用于快速验证概念(注:官网已迁移至 `https://react.dev/`,且 React 19 起官方不再发布预构建 UMD 包,浏览器直连需改用 ESM CDN 或构建工具)。
常见公共 CDN 包括 Cloudflare cdnjs(原参考段落误标为字节跳动 CDN,实际示例链接为 `cdnjs.cloudflare.com` 的 React 18.2.0 生产版与 Babel Standalone 6.26.0)、Staticfile CDN(`cdn.staticfile.org` 的 React 18.2.0 开发版)以及 unpkg(示例中为 React 16 早期开发版链接)。无论选用哪家镜像,都必须牢记:在浏览器端依赖 `babel-standalone` 实时编译 JSX 会带来明显的解析与执行开销,仅适用于快速原型或教学演示,严禁用于正式生产环境。
单页 HTML 实例、核心库职责与 createRoot 解析
典型单页实例在一个标准 HTML 文档的 `<head>` 中按顺序引入三个库:`react.production.min.js`(或开发版 `react.development.js`)提供 React 核心 API;`react-dom.production.min.js` 提供浏览器 DOM 挂载能力;`babel.min.js`(Babel Standalone)将 ES6 与 JSX 转译为浏览器可直接执行的标准 JavaScript(早期编辑器生态也常配合 `babel-sublime` 等插件获得 JSX 高亮)。注意完整 HTML 文档末尾只需闭合一次 `</script></body></html>`,避免复制粘贴导致的重复闭合标签。
挂载过程分为三步:首先用 `document.getElementById("example")` 获取目标 DOM 容器;接着调用 React 18 新增的 `ReactDOM.createRoot(container)` 创建并发根节点并存入 `root` 变量;最后执行 `root.render(<App />)` 把组件产出的 `<h1>Hello, React!</h1>` 插入容器。特别注意:凡是包含 JSX 语法的内联脚本,`<script>` 标签必须标注 `type="text/babel"`——本站离线 Chromium 实测证实,浏览器原生 JS 引擎会跳过 `type="text/babel"` 脚本(`executedNatively=false`、容器保持空白),待离线转译器将 JSX 转换为 `React.createElement("h1", null, "Hello, React!")` 与 `React.createElement(App, null)` 后再执行,即可在 `#example` 内精确渲染 `<h1>Hello, React!</h1>`;预编译路径则在零运行时转译步数下产出完全一致的 DOM。
在离线 Chromium 中验证 type="text/babel" 行为、JSX 到 createElement 转译与 createRoot 挂载
"""Offline Playwright Chromium lab for React Ch 05 (install-cdn)."""
from __future__ import annotations
import json
from playwright.sync_api import sync_playwright
MICRO_REACT_JS = r"""
var React = (() => {
function createElement(type, props, ...children) {
const flat = [];
children.forEach((c) => {
if (Array.isArray(c)) flat.push(...c);
else if (c !== null && c !== undefined && c !== false && c !== true) flat.push(c);
});
return { type, props: Object.assign({}, props || {}, { children: flat }) };
}
function resolveTree(node) {
if (typeof node === "string" || typeof node === "number") return { type: "#text", text: String(node) };
if (typeof node.type === "function") return resolveTree(node.type(node.props));
return { type: node.type, props: node.props, children: (node.props.children || []).map(resolveTree) };
}
function createDom(vnode) {
if (vnode.type === "#text") return document.createTextNode(vnode.text);
const el = document.createElement(vnode.type);
for (const [k, v] of Object.entries(vnode.props || {})) {
if (k === "children") continue;
el.setAttribute(k === "className" ? "class" : k, String(v));
}
vnode.children.forEach((c) => el.appendChild(createDom(c)));
return el;
}
function createRoot(container) {
return {
render(element) {
container.innerHTML = "";
container.appendChild(createDom(resolveTree(element)));
},
};
}
return { createElement, 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: Validate <script type="text/babel"> is NOT executed natively by browser JS engine
page.set_content("""<!DOCTYPE html>
<html><body>
<div id="example"></div>
<script>window.__babelExecutedNatively = false;</script>
<script type="text/babel">
window.__babelExecutedNatively = true;
function App() { return <h1>Hello, React!</h1>; }
const root = ReactDOM.createRoot(document.getElementById("example"));
root.render(<App />);
</script>
</body></html>""")
actual1 = page.evaluate("""() => {
const s = document.querySelector("script[type='text/babel']");
return {
executedNatively: window.__babelExecutedNatively,
scriptType: s ? s.getAttribute("type") : null,
hasCreateRootCall: s ? s.textContent.includes("ReactDOM.createRoot") : false,
containerStillEmpty: document.getElementById("example").innerHTML === ""
};
}""")
expected1 = {
"executedNatively": False,
"scriptType": "text/babel",
"hasCreateRootCall": True,
"containerStillEmpty": True,
}
cases.append({
"name": "cdn_script_tag_contract",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Offline JSX-to-createElement transpilation equivalence
page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="example"></div>
<script type="text/babel" id="src-jsx">
function App() {{
return <h1>Hello, React!</h1>;
}}
const root = ReactDOM.createRoot(document.getElementById("example"));
root.render(<App />);
</script>
<script>{MICRO_REACT_JS}
function transpileSimpleJsx(src) {{
return src
.replace(/<([a-z][a-z0-9]*)>([^<]*)<\\/\\1>/g, 'React.createElement("$1", null, "$2")')
.replace(/<([A-Z][A-Za-z0-9]*)\\s*\\/>/g, 'React.createElement($1, null)');
}}
const raw = document.getElementById("src-jsx").textContent;
const compiled = transpileSimpleJsx(raw);
window.__compiled = compiled;
eval(compiled);
</script></body></html>""")
actual2 = page.evaluate("""() => ({
containsCreateElementH1: window.__compiled.includes('React.createElement("h1", null, "Hello, React!")'),
containsCreateElementApp: window.__compiled.includes('React.createElement(App, null)'),
renderedText: document.querySelector("#example h1").textContent
})""")
expected2 = {
"containsCreateElementH1": True,
"containsCreateElementApp": True,
"renderedText": "Hello, React!",
}
cases.append({
"name": "jsx_to_create_element_transpile",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: React 18 createRoot mount into #example
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="example"></div>
<script>{MICRO_REACT_JS}
function App() {{
return React.createElement("h1", null, "Hello, React!");
}}
const container = document.getElementById("example");
const root = ReactDOM.createRoot(container);
root.render(React.createElement(App, null));
</script></body></html>""")
actual3 = page.evaluate("""() => {
const ex = document.getElementById("example");
return {
containerId: ex.id,
childTag: ex.firstElementChild.tagName,
childText: ex.firstElementChild.textContent
};
}""")
expected3 = {
"containerId": "example",
"childTag": "H1",
"childText": "Hello, React!",
}
cases.append({
"name": "create_root_mount_example",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: In-browser transpile step vs precompiled createElement equivalence
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="a"></div><div id="b"></div>
<script>{MICRO_REACT_JS}
let transpileCalls = 0;
function compileAtRuntime(src) {{
transpileCalls += 1;
return src.replace(/<h1>([^<]*)<\\/h1>/g, 'React.createElement("h1", null, "$1")');
}}
const jsxOut = eval(compileAtRuntime('<h1>Hello, React!</h1>'));
ReactDOM.createRoot(document.getElementById("a")).render(jsxOut);
const precompiledSteps = 0;
ReactDOM.createRoot(document.getElementById("b")).render(React.createElement("h1", null, "Hello, React!"));
window.__cmp = {{
runtimeTranspileSteps: transpileCalls,
precompiledTranspileSteps: precompiledSteps,
sameHtml: document.getElementById("a").innerHTML === document.getElementById("b").innerHTML,
html: document.getElementById("b").innerHTML
}};
</script></body></html>""")
actual4 = page.evaluate("() => window.__cmp")
expected4 = {
"runtimeTranspileSteps": 1,
"precompiledTranspileSteps": 0,
"sameHtml": True,
"html": "<h1>Hello, React!</h1>",
}
cases.append({
"name": "babel_runtime_overhead_vs_precompiled",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对原生浏览器不直接执行 type="text/babel" 脚本、离线 JSX 转译产出 React.createElement 并渲染 <h1>Hello, React!</h1>,以及预编译与运行时转译 HTML 输出一致。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a79ccdde2ae64ede275e74c0731db85fb764f709ccfec79d1245b69da8912fb0
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ffdce01eaaf1b587271b36a60b45b47ae16a1640b349ad4ce21622a179eaa834
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么使用 CDN 编写 JSX 时必须给 <script> 加上 type="text/babel",且线上项目不应依赖该方式?
展开参考解答
原生浏览器 JS 引擎无法解析 JSX 语法,设置 type="text/babel" 可阻止浏览器直接报错并交由 Babel Standalone 扫描转译;但浏览器端即时编译会显著拖慢首屏加载与执行性能,正式环境应在构建阶段预编译 JSX。