Files
React/scripts/import-react.mjs

608 lines
24 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Imports the React documentation (react.dev and its Simplified Chinese translation) into this VitePress site.
//
// node scripts/import-react.mjs <react.dev-repo> [<zh-hans.react.dev-repo>]
//
// <react.dev-repo> English pages -> src/, images -> src/public/, sidebar -> scripts/nav.json
// <zh-hans.react.dev-repo> Chinese pages -> i18n/zh/, Chinese sidebar titles -> scripts/nav.json
//
// react.dev pages are MDX. They are rewritten for VitePress (Markdown + Vue):
// - `## Title {/*id*/}` -> `## Title {#id}`
// - `{/* comment */}` -> removed
// - <Sandpack> (and its variants) -> ::: code-group, one tab per visible file
// - <TerminalBlock> -> ```bash code block
// - JSX attributes `x={expr}` -> Vue bindings `:x="expr"`, `className` -> `class`
// - code block meta `[[1, 2, "x"]]`, `{expectedErrors: ...}` -> removed
// - frontmatter `title` -> `# title` heading (react.dev renders it from frontmatter)
// The remaining react.dev components (<Intro>, <Note>, <Pitfall>, <DeepDive>, <Challenges>, <Diagram>...)
// are implemented as Vue components in .vitepress/theme/react/.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SITE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SRC_DIR = path.join(SITE_DIR, 'src');
const ZH_DIR = path.join(SITE_DIR, 'i18n', 'zh');
const NAV_FILE = path.join(SITE_DIR, 'scripts', 'nav.json');
// Sidebars of the sections shown on this site, in nav bar order.
const SIDEBARS = [
{ file: 'sidebarLearn.json', base: '/learn/' },
{ file: 'sidebarReference.json', base: '/reference/' },
{ file: 'sidebarCommunity.json', base: '/community/' },
{ file: 'sidebarBlog.json', base: '/blog/' },
];
// Files from react.dev's public/ that pages and the site use.
const PUBLIC_ENTRIES = ['images', 'favicon.ico', 'favicon-16x16.png', 'favicon-32x32.png', 'apple-touch-icon.png'];
// The React logo (react.dev draws it inline in Logo.tsx).
const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="-11.5 -10.23174 23 20.46348">
<circle r="2.05" fill="#58c4dc"/>
<g stroke="#58c4dc" stroke-width="1" fill="none">
<ellipse rx="11" ry="4.2"/>
<ellipse rx="11" ry="4.2" transform="rotate(60)"/>
<ellipse rx="11" ry="4.2" transform="rotate(120)"/>
</g>
</svg>
`;
// react.dev builds its home page from React components (HomeContent.js); VitePress uses a home layout instead.
const HOME = {
en: `---
layout: home
title: React
titleTemplate: The library for web and native user interfaces
hero:
name: React
text: The library for web and native user interfaces
image:
src: /logo.svg
alt: React
actions:
- theme: brand
text: Learn React
link: /learn
- theme: alt
text: API Reference
link: /reference/react
features:
- title: Create user interfaces from components
details: React lets you build user interfaces out of individual pieces called components. Create your own React components, then combine them into entire screens, pages, and apps.
link: /learn/describing-the-ui
- title: Write components with code and markup
details: React components are JavaScript functions. The markup syntax is called JSX, a JavaScript syntax extension popularized by React.
link: /learn/writing-markup-with-jsx
- title: Add interactivity wherever you need it
details: React components receive data and return what should appear on the screen. You can pass them new data in response to an interaction, and React updates the screen to match.
link: /learn/adding-interactivity
- title: Go full-stack with a framework
details: React is a library. To build an entire app with React, we recommend a full-stack React framework like Next.js or React Router.
link: /learn/creating-a-react-app
- title: Use the best from every platform
details: React lets you build both web apps and native apps using the same skills, leveraging each platform's unique strengths.
link: /learn/react-developer-tools
- title: Upgrade when the future is ready
details: React approaches changes with care. Every React commit is tested on business-critical surfaces with over a billion users.
link: /blog
---
`,
zh: `---
layout: home
title: React
titleTemplate: 用于构建 Web 和原生交互界面的库
hero:
name: React
text: 用于构建 Web 和原生交互界面的库
image:
src: /logo.svg
alt: React
actions:
- theme: brand
text: 学习 React
link: /learn
- theme: alt
text: API 参考
link: /reference/react
features:
- title: 用组件创建用户界面
details: React 让你可以通过组件来构建用户界面。你可以创建自己的 React 组件,然后将它们组合成整个屏幕、页面和应用程序。
link: /learn/describing-the-ui
- title: 用代码和标签编写组件
details: React 组件是 JavaScript 函数。这种标签语法被称为 JSX,它是由 React 推广的 JavaScript 语法扩展。
link: /learn/writing-markup-with-jsx
- title: 在任何地方添加交互
details: React 组件接收数据并返回应该出现在屏幕上的内容。你可以通过响应交互向它们传递新数据,React 会更新屏幕以匹配新数据。
link: /learn/adding-interactivity
- title: 使用框架进行全栈开发
details: React 是一个库。要使用 React 构建整个应用程序,我们推荐使用 Next.js 或 React Router 等全栈 React 框架。
link: /learn/creating-a-react-app
- title: 充分利用每个平台的优势
details: React 让你使用相同的技能构建 Web 应用和原生应用,充分利用每个平台的独特优势。
link: /learn/react-developer-tools
- title: 在未来准备好时升级
details: React 非常谨慎地处理每个改动。每个 React 提交都在拥有超过十亿用户的关键业务页面上进行测试。
link: /blog
---
`,
};
// ---------------------------------------------------------------------------------------------
// MDX -> VitePress Markdown
const SANDPACK_TAGS = ['Sandpack', 'SandpackRSC', 'SandpackWithHTMLOutput'];
// react.dev components whose children are Markdown. A blank line after the opening tag and before
// the closing tag makes markdown-it parse the children as Markdown instead of raw HTML.
const BLOCK_COMPONENTS = new Set([
'Intro', 'YouWillLearn', 'Recap', 'Note', 'Pitfall', 'Deprecated', 'Wip', 'Canary', 'RC', 'Experimental',
'NextMajor', 'RSC', 'DeepDive', 'Challenges', 'Recipes', 'Hint', 'Solution', 'LearnMore', 'Diagram',
'DiagramGroup', 'CodeDiagram', 'FullWidth', 'MaxWidth', 'ConsoleBlock', 'ConsoleBlockMulti', 'ConsoleLogLine',
'BlogCard', 'YouWillLearnCard', 'PackageImport', 'IllustrationBlock',
]);
// Plain-text children: kept on one HTML block, with the indentation removed.
const TEXT_COMPONENTS = new Set(['TeamMember']);
function findMatching(text, start, open, close) {
let depth = 0;
let quote = null;
for (let i = start; i < text.length; i++) {
const ch = text[i];
if (quote) {
if (ch === '\\') i++;
else if (ch === quote) quote = null;
continue;
}
if (ch === '"' || ch === '\'' || ch === '`') quote = ch;
else if (ch === open) depth++;
else if (ch === close && --depth === 0) return i;
}
return -1;
}
function escapeAttr(value) {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
}
// `name={expr}` -> `name="literal"` or `:name="expr"`.
function convertJsxAttributes(tag) {
let out = '';
let i = 0;
const attr = /(\s)([A-Za-z_:][\w:.-]*)=\{/g;
let m;
while ((m = attr.exec(tag))) {
const braceStart = m.index + m[0].length - 1;
const braceEnd = findMatching(tag, braceStart, '{', '}');
if (braceEnd === -1) break;
let name = m[2] === 'className' ? 'class' : m[2];
const expr = tag.slice(braceStart + 1, braceEnd).trim();
out += tag.slice(i, m.index) + m[1];
const literal = expr.match(/^(["'])((?:(?!\1)[^\\]|\\.)*)\1$/);
if (literal) out += `${name}="${escapeAttr(literal[2])}"`;
else out += `:${name}="${escapeAttr(expr)}"`;
i = braceEnd + 1;
attr.lastIndex = i;
}
return (out + tag.slice(i)).replace(/(\s)className=/g, '$1class=');
}
// Applies `fn` to the parts of a line outside inline code spans.
function outsideInlineCode(line, fn) {
return line.split(/(`+[^`]*`+)/).map((part, i) => (i % 2 ? part : fn(part))).join('');
}
// Whether the tag that starts the line ends on it (">" outside quotes and braces).
function tagIsClosed(line) {
let depth = 0;
let quote = null;
for (let j = line.indexOf('<') + 1; j < line.length; j++) {
const ch = line[j];
if (quote) { if (ch === quote) quote = null; continue; }
if (depth === 0 && (ch === '"' || ch === '\'')) quote = ch;
else if (ch === '{') depth++;
else if (ch === '}') depth--;
else if (ch === '>' && depth === 0) return true;
}
return false;
}
// Index of the first "{/*" outside inline code, or -1.
function commentStart(line, from = 0) {
for (let i = line.indexOf('{/*', from); i !== -1; i = line.indexOf('{/*', i + 1)) {
if (((line.slice(0, i).match(/`/g) ?? []).length % 2) === 0) return i;
}
return -1;
}
// Removes MDX comments {/* ... */} from a line. Returns [line, stillOpen].
function stripComments(line) {
for (let start = commentStart(line); start !== -1; start = commentStart(line, start)) {
const end = line.indexOf('*/}', start);
if (end === -1) return [line.slice(0, start), true];
line = line.slice(0, start) + line.slice(end + 3);
}
return [line, false];
}
// JSX string expressions in text, such as {' '}at App or {'\n'}: keep the text, as HTML.
function convertStringExpressions(text) {
return text.replace(/\{(['"])((?:(?!\1)[^\\]|\\.)*)\1\}/g, (_, quote, str) => str
.replace(/\\n/g, '<br>')
.replace(/\\(.)/g, '$1')
.replace(/</g, '&lt;')
.replace(/ /g, '&nbsp;'));
}
function convertTags(text) {
// Tags are found with a brace-aware scan so attribute values like style={{a: 1}} stay intact.
let out = '';
let i = 0;
const tagStart = /<([A-Za-z][\w.]*)(?=[\s/>])/g;
let m;
while ((m = tagStart.exec(text))) {
let j = m.index + m[0].length;
let depth = 0;
let quote = null;
for (; j < text.length; j++) {
const ch = text[j];
if (quote) { if (ch === quote) quote = null; continue; }
if (depth === 0 && (ch === '"' || ch === '\'')) quote = ch;
else if (ch === '{') depth++;
else if (ch === '}') depth--;
else if (ch === '>' && depth === 0) break;
}
if (j >= text.length) break;
out += text.slice(i, m.index) + convertJsxAttributes(text.slice(m.index, j + 1));
i = j + 1;
tagStart.lastIndex = i;
}
return out + text.slice(i);
}
// Cleans a code block's info string. Returns { lang, file, hidden, active, lines }.
function parseFenceInfo(info) {
let rest = info.trim();
// Remove react.dev-only metadata: [[step, line, "text"]], [3, 5], {expectedErrors: {...}}.
for (;;) {
const bracket = rest.search(/\[\s*[\[\d]/);
if (bracket === -1) break;
const end = findMatching(rest, bracket, '[', ']');
if (end === -1) { rest = rest.slice(0, bracket); break; }
rest = rest.slice(0, bracket) + rest.slice(end + 1);
}
for (;;) {
const brace = rest.search(/\{\s*[A-Za-z]/);
if (brace === -1) break;
const end = findMatching(rest, brace, '{', '}');
if (end === -1) { rest = rest.slice(0, brace); break; }
rest = rest.slice(0, brace) + rest.slice(end + 1);
}
const lines = (rest.match(/\{([\d,\s-]+)\}/) ?? [])[1]?.replace(/\s/g, '');
rest = rest.replace(/\{[^}]*\}?/g, ' ');
const words = rest.split(/\s+/).filter(Boolean);
const lang = words.shift() ?? '';
const hidden = words.includes('hidden');
const active = words.includes('active');
const file = words.find(word => /[./]/.test(word) && word !== 'hidden' && word !== 'active');
return { lang, file, hidden, active, lines };
}
function fenceOpen(fence, { lang, lines }, label) {
return `${fence}${lang || 'text'}${lines ? `{${lines}}` : ''}${label ? ` [${label}]` : ''}`;
}
// Converts the fenced code blocks of a <Sandpack> to a VitePress code group.
function convertSandpack(body, indent) {
const files = [];
const other = [];
for (let i = 0; i < body.length; i++) {
const open = body[i].match(/^(\s*)(`{3,}|~{3,})(.*)$/);
if (!open) {
const [text] = stripComments(body[i]);
if (text.trim()) other.push(text);
continue;
}
const [, , fence, info] = open;
const code = [];
for (i++; i < body.length && !(body[i].trim().startsWith(fence) && body[i].trim().replace(/[`~]/g, '') === ''); i++)
code.push(body[i].slice(Math.min(open[1].length, body[i].length - body[i].trimStart().length)));
files.push({ fence, info: parseFenceInfo(info), code });
}
let visible = files.filter(file => !file.info.hidden);
if (!visible.length) visible = files;
const out = [`${indent}::: code-group`, ''];
visible.forEach((file, n) => {
const name = (file.info.file ?? (n === 0 ? '/src/App.js' : `file${n}.${file.info.lang || 'txt'}`))
.replace(/^\/?(src\/)?/, '');
const fence = file.fence.length > 3 ? file.fence : '```';
out.push(indent + fenceOpen(fence, file.info, name), ...file.code.map(line => (line ? indent + line : line)), indent + fence, '');
});
out.push(`${indent}:::`);
if (other.length) out.push('', ...other);
return out;
}
function closingIndex(lines, from, tag) {
const close = new RegExp(`</${tag}>`);
for (let i = from; i < lines.length; i++)
if (close.test(lines[i])) return i;
return -1;
}
export function convertMdx(source, { title: forcedTitle } = {}) {
let text = source.replace(/\r\n/g, '\n').replace(/^/, '');
let frontmatter = '';
const fm = text.match(/^---\n[\s\S]*?\n---\n/);
if (fm) {
frontmatter = fm[0];
text = text.slice(fm[0].length);
}
const title = forcedTitle ?? frontmatter.match(/^title:\s*(.*)$/m)?.[1].trim().replace(/^(['"])(.*)\1$/, '$2');
const lines = text.split('\n');
const out = [];
let fence = null;
let comment = false;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
// Fenced code blocks are copied as-is, except for their info string.
const fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})(.*)$/);
if (fence) {
out.push(line);
if (fenceMatch && fenceMatch[2].startsWith(fence) && !fenceMatch[3].trim()) fence = null;
continue;
}
if (fenceMatch && !comment) {
fence = fenceMatch[2];
out.push(fenceOpen(fenceMatch[1] + fenceMatch[2], parseFenceInfo(fenceMatch[3])));
continue;
}
// MDX comments {/* ... */}, possibly over several lines.
if (comment) {
const end = line.indexOf('*/}');
if (end === -1) continue;
line = line.slice(end + 3);
comment = false;
if (!line.trim()) continue;
}
// An opening tag that continues on the next lines (long alt text) is joined into one line.
if (/^\s*<[A-Za-z]/.test(line)) {
while (!tagIsClosed(line) && i + 1 < lines.length && lines[i + 1].trim())
line = `${line} ${lines[++i].trim()}`;
}
const indent = line.match(/^\s*/)[0];
const sandpack = line.match(/^\s*<(Sandpack\w*)\b[^>]*>\s*$/);
if (sandpack && SANDPACK_TAGS.includes(sandpack[1])) {
const end = closingIndex(lines, i + 1, sandpack[1]);
if (end !== -1) {
if (out.length && out[out.length - 1].trim()) out.push('');
out.push(...convertSandpack(lines.slice(i + 1, end), indent));
i = end;
continue;
}
}
const terminal = line.match(/^\s*<TerminalBlock>(.*)$/);
if (terminal) {
const end = closingIndex(lines, i, 'TerminalBlock');
const body = end === i
? [terminal[1].replace(/<\/TerminalBlock>.*$/, '')]
: [terminal[1], ...lines.slice(i + 1, end), lines[end].replace(/<\/TerminalBlock>.*$/, '')];
out.push(`${indent}\`\`\`bash`, ...body.map(l => l.trim()).filter(Boolean).map(l => indent + l), `${indent}\`\`\``);
i = end;
continue;
}
// Plain-text components (<TeamMember>): one HTML block without indentation.
const textTag = line.match(/^\s*<([A-Z]\w*)\b/);
if (textTag && TEXT_COMPONENTS.has(textTag[1])) {
const end = /\/>\s*$/.test(line) ? i : closingIndex(lines, i, textTag[1]);
// Markdown is not parsed inside the HTML block, so inline code becomes <code>.
const block = lines.slice(i, end + 1).map(l => l.trim()).filter(Boolean).join('\n')
.replace(/`([^`]+)`/g, (_, code) => `<code>${code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`);
if (out.length && out[out.length - 1].trim()) out.push('');
out.push(convertTags(block), '');
i = end;
continue;
}
// Heading ids: "## Title {/*title*/}" -> "## Title {#title}".
if (/^#{1,6}\s/.test(line)) {
line = line.replace(/\s*\{\/\*\s*([^*]*?)\s*\*\/\}\s*$/, (_, id) => (id ? ` {#${id}}` : ''));
}
// Remove MDX comments outside inline code.
const hadComment = commentStart(line) !== -1;
[line, comment] = stripComments(line);
if (hadComment && !line.trim()) continue;
// A line that starts with a tag is converted whole: attribute values may contain backticks.
line = /^\s*<[A-Za-z]/.test(line)
? convertTags(line)
: outsideInlineCode(line, part => convertTags(convertStringExpressions(part)));
// Give block components blank lines around their children.
const blockOpen = line.match(/^\s*<([A-Z]\w*)\b[^>]*[^/]>\s*$|^\s*<([A-Z]\w*)>\s*$/);
const blockClose = line.match(/^\s*<\/([A-Z]\w*)>\s*$/);
const blockName = blockOpen ? blockOpen[1] ?? blockOpen[2] : blockClose?.[1];
if (blockName && BLOCK_COMPONENTS.has(blockName)) {
if (out.length && out[out.length - 1].trim()) out.push('');
out.push(line);
if (i + 1 < lines.length && lines[i + 1].trim()) out.push('');
continue;
}
// Static files are served from the site root (the tutorial writes "../images/...").
out.push(line.replace(/(\]\(|\bsrc=")(?:\.\.?\/)+(images\/)/g, '$1/$2'));
}
let body = out.join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '');
// The title heading gets a fixed id: its slug would often repeat a heading id on the page
// (useMemo.md has "## `useMemo(...)` {#usememo}"), which VitePress rejects.
if (title && !/^#\s/m.test(body.split('\n').find(l => l.trim()) ?? ''))
body = `# ${title.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')} {#page-title}\n\n${body}`;
return frontmatter + (frontmatter ? '\n' : '') + body.replace(/\s*$/, '\n');
}
// ---------------------------------------------------------------------------------------------
// Pages
function listMarkdown(dir, rel = '') {
const files = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const entryRel = rel ? `${rel}/${entry.name}` : entry.name;
if (entry.isDirectory()) files.push(...listMarkdown(path.join(dir, entry.name), entryRel));
else if (entry.name.endsWith('.md')) files.push(entryRel);
}
return files;
}
function write(file, text) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text);
}
// Number of Han characters outside code blocks: a page counts as translated with at least this many.
const MIN_CHINESE_CHARS = 50;
function chineseChars(text) {
const prose = text.replace(/^(\s*)(`{3,}|~{3,})[\s\S]*?^\1\2\s*$/gm, '');
return (prose.match(/\p{Script=Han}/gu) ?? []).length;
}
function importEnglish(repo) {
const contentDir = path.join(repo, 'src', 'content');
fs.rmSync(SRC_DIR, { recursive: true, force: true });
const pages = listMarkdown(contentDir);
for (const rel of pages) {
const text = rel === 'index.md' ? HOME.en : convertMdx(fs.readFileSync(path.join(contentDir, rel), 'utf8'));
write(path.join(SRC_DIR, rel), text);
}
const publicDir = path.join(SRC_DIR, 'public');
for (const entry of PUBLIC_ENTRIES) {
const from = path.join(repo, 'public', entry);
if (fs.existsSync(from)) fs.cpSync(from, path.join(publicDir, entry), { recursive: true });
}
write(path.join(publicDir, 'logo.svg'), LOGO_SVG);
console.log(`[import] ${pages.length} English pages written to src/.`);
return new Set(pages);
}
function importChinese(repo, englishPages) {
const contentDir = path.join(repo, 'src', 'content');
fs.rmSync(ZH_DIR, { recursive: true, force: true });
let count = 0;
const skipped = [];
for (const rel of listMarkdown(contentDir)) {
if (!englishPages.has(rel)) {
skipped.push(`${rel} (no English page)`);
continue;
}
if (rel === 'index.md') {
write(path.join(ZH_DIR, rel), HOME.zh);
count++;
continue;
}
const source = fs.readFileSync(path.join(contentDir, rel), 'utf8');
if (chineseChars(source) < MIN_CHINESE_CHARS) {
skipped.push(`${rel} (not translated)`);
continue;
}
write(path.join(ZH_DIR, rel), convertMdx(source));
count++;
}
// Translations may lag behind and still use images that react.dev has since removed.
const zhImages = path.join(repo, 'public', 'images');
if (fs.existsSync(zhImages))
fs.cpSync(zhImages, path.join(SRC_DIR, 'public', 'images'), { recursive: true, force: false, errorOnExist: false });
console.log(`[import] ${count} Chinese pages written to i18n/zh/; ${skipped.length} skipped:`);
for (const line of skipped) console.log(` ${line}`);
}
// ---------------------------------------------------------------------------------------------
// Sidebar
function routeTitles(routes, byPath = new Map(), headers = []) {
for (const route of routes) {
if (route.hasSectionHeader) headers.push(route.sectionHeader);
if (route.path && route.title) byPath.set(route.path, route.title);
if (route.routes) routeTitles(route.routes, byPath, headers);
}
return { byPath, headers };
}
function toNav(routes, zh, headerIndex = { n: 0 }) {
const items = [];
let group = null;
for (const route of routes) {
if (route.hasSectionHeader) {
const text = route.sectionHeader;
group = { text, zh: zh?.headers[headerIndex.n++], items: [] };
items.push(group);
continue;
}
if (!route.title) continue;
const item = { text: route.title };
const zhText = zh?.byPath.get(route.path);
if (zhText && zhText !== route.title) item.zh = zhText;
if (route.path) item.link = route.path;
if (route.version) item.version = route.version;
if (route.routes?.length) item.items = toNav(route.routes, zh, headerIndex);
(group ? group.items : items).push(item);
}
return items;
}
// Sidebars write the React version as {{version}}; react.dev fills it in from src/siteConfig.js.
function readSidebar(repo, file, version) {
const text = fs.readFileSync(path.join(repo, 'src', file), 'utf8');
return JSON.parse(text.replace(/\{\{version\}\}/g, version));
}
function importSidebars(repo, zhRepo) {
const version = fs.readFileSync(path.join(repo, 'src', 'siteConfig.js'), 'utf8').match(/version:\s*'([^']+)'/)?.[1];
if (!version) throw new Error('React version not found in src/siteConfig.js.');
const nav = SIDEBARS.map(({ file, base }) => {
const sidebar = readSidebar(repo, file, version);
const zhFile = zhRepo && path.join(zhRepo, 'src', file);
const zhSidebar = zhFile && fs.existsSync(zhFile) ? readSidebar(zhRepo, file, version) : null;
const zh = zhSidebar ? routeTitles(zhSidebar.routes) : null;
// Section headers are matched by position, so only use them when both sidebars have the same number.
if (zh && zh.headers.length !== routeTitles(sidebar.routes).headers.length) zh.headers = [];
return {
text: sidebar.title,
zh: zhSidebar?.title,
base,
items: toNav(sidebar.routes, zh),
};
});
fs.writeFileSync(NAV_FILE, JSON.stringify(nav, null, 2) + '\n');
console.log('[import] Sidebar written to scripts/nav.json.');
}
function main() {
const [repo, zhRepo] = process.argv.slice(2).map(arg => path.resolve(arg));
if (!repo || !fs.existsSync(path.join(repo, 'src', 'content')))
throw new Error('Usage: node scripts/import-react.mjs <react.dev-repo> [<zh-hans.react.dev-repo>]');
if (zhRepo && !fs.existsSync(path.join(zhRepo, 'src', 'content')))
throw new Error(`${zhRepo} is not a zh-hans.react.dev checkout (src/content is missing).`);
const englishPages = importEnglish(repo);
if (zhRepo) importChinese(zhRepo, englishPages);
importSidebars(repo, zhRepo);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url))
main();