mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-10 07:37:19 +02:00
polish(v2): improve Docusaurus 1 to 2 migration developer experience (#2884)
* improve markdown parsing errors by adding file path to error * typo commit * Add default nav item position to right (as v1) * improve error when sidebar references unexisting document * parseMarkdownFile: improve errors by providing hint about using "" to avoid parsing errors, if using special characters * improve subcategory migration error for Unknown sidebar item type * improve unrecognizedFields error * typo * fix inline snapshots * improve the migration docs * improve the migration docs * improve migration doc * Update migrating-from-v1-to-v2.md Co-authored-by: Yangshun Tay <tay.yang.shun@gmail.com>
This commit is contained in:
parent
8aa520c314
commit
1003a15d1f
11 changed files with 195 additions and 46 deletions
|
@ -12,7 +12,7 @@ import readingTime from 'reading-time';
|
|||
import {Feed} from 'feed';
|
||||
import {PluginOptions, BlogPost, DateLink} from './types';
|
||||
import {
|
||||
parse,
|
||||
parseMarkdownFile,
|
||||
normalizeUrl,
|
||||
aliasedSitePath,
|
||||
getEditUrl,
|
||||
|
@ -120,8 +120,7 @@ export async function generateBlogPosts(
|
|||
|
||||
const editBlogUrl = getEditUrl(relativePath, editUrl);
|
||||
|
||||
const fileString = await fs.readFile(source, 'utf-8');
|
||||
const {frontMatter, content, excerpt} = parse(fileString);
|
||||
const {frontMatter, content, excerpt} = await parseMarkdownFile(source);
|
||||
|
||||
if (frontMatter.draft && process.env.NODE_ENV === 'production') {
|
||||
return;
|
||||
|
|
|
@ -109,6 +109,16 @@ Array [
|
|||
]
|
||||
`;
|
||||
|
||||
exports[`site with wrong sidebar file 1`] = `
|
||||
[Error: Bad sidebars file. The document id 'goku' was used in the sidebar, but no document with this id could be found.
|
||||
Available document ids=
|
||||
- foo/bar
|
||||
- foo/baz
|
||||
- hello
|
||||
- ipsum
|
||||
- lorem]
|
||||
`;
|
||||
|
||||
exports[`versioned website content 1`] = `
|
||||
Array [
|
||||
Object {
|
||||
|
|
|
@ -45,13 +45,7 @@ test('site with wrong sidebar file', async () => {
|
|||
const plugin = pluginContentDocs(context, {
|
||||
sidebarPath,
|
||||
});
|
||||
return plugin
|
||||
.loadContent()
|
||||
.catch((e) =>
|
||||
expect(e).toMatchInlineSnapshot(
|
||||
`[Error: Improper sidebars file, document with id 'goku' not found.]`,
|
||||
),
|
||||
);
|
||||
return plugin.loadContent().catch((e) => expect(e).toMatchSnapshot());
|
||||
});
|
||||
|
||||
describe('empty/no docs website', () => {
|
||||
|
|
|
@ -109,7 +109,7 @@ describe('loadSidebars', () => {
|
|||
expect(() =>
|
||||
loadSidebars([sidebarPath]),
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"Unknown sidebar item type: superman"`,
|
||||
`"Unknown sidebar item type [superman]. Sidebar item={\\"type\\":\\"superman\\"} "`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
@ -275,16 +275,18 @@ export default function pluginContentDocs(
|
|||
});
|
||||
|
||||
const convertDocLink = (item: SidebarItemDoc): SidebarItemLink => {
|
||||
const linkID = item.id;
|
||||
const linkMetadata = docsMetadataRaw[linkID];
|
||||
const docId = item.id;
|
||||
const docMetadata = docsMetadataRaw[docId];
|
||||
|
||||
if (!linkMetadata) {
|
||||
if (!docMetadata) {
|
||||
throw new Error(
|
||||
`Improper sidebars file, document with id '${linkID}' not found.`,
|
||||
`Bad sidebars file. The document id '${docId}' was used in the sidebar, but no document with this id could be found.
|
||||
Available document ids=
|
||||
- ${Object.keys(docsMetadataRaw).sort().join('\n- ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
const {title, permalink, sidebar_label} = linkMetadata;
|
||||
const {title, permalink, sidebar_label} = docMetadata;
|
||||
|
||||
return {
|
||||
type: 'link',
|
||||
|
|
|
@ -5,10 +5,9 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import {
|
||||
parse,
|
||||
parseMarkdownFile,
|
||||
aliasedSitePath,
|
||||
normalizeUrl,
|
||||
getEditUrl,
|
||||
|
@ -65,7 +64,7 @@ export default async function processMetadata({
|
|||
const {versioning} = env;
|
||||
const filePath = path.join(refDir, source);
|
||||
|
||||
const fileStringPromise = fs.readFile(filePath, 'utf-8');
|
||||
const fileMarkdownPromise = parseMarkdownFile(filePath);
|
||||
const lastUpdatedPromise = lastUpdated(filePath, options);
|
||||
|
||||
let version;
|
||||
|
@ -92,7 +91,7 @@ export default async function processMetadata({
|
|||
|
||||
const docsEditUrl = getEditUrl(relativePath, editUrl);
|
||||
|
||||
const {frontMatter = {}, excerpt} = parse(await fileStringPromise);
|
||||
const {frontMatter = {}, excerpt} = await fileMarkdownPromise;
|
||||
const {sidebar_label, custom_edit_url} = frontMatter;
|
||||
|
||||
// Default base id is the file name.
|
||||
|
|
|
@ -136,7 +136,15 @@ function normalizeItem(item: SidebarItemRaw): SidebarItem[] {
|
|||
assertIsDoc(item);
|
||||
return [item];
|
||||
default:
|
||||
throw new Error(`Unknown sidebar item type: ${item.type}`);
|
||||
const extraMigrationError =
|
||||
item.type === 'subcategory'
|
||||
? "Docusaurus v2: 'subcategory' has been renamed as 'category'"
|
||||
: '';
|
||||
throw new Error(
|
||||
`Unknown sidebar item type [${
|
||||
item.type
|
||||
}]. Sidebar item=${JSON.stringify(item)} ${extraMigrationError}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -20,6 +20,9 @@ import useLogo from '@theme/hooks/useLogo';
|
|||
|
||||
import styles from './styles.module.css';
|
||||
|
||||
// retrocompatible with v1
|
||||
const DefaultNavItemPosition = 'right';
|
||||
|
||||
function NavLink({
|
||||
activeBasePath,
|
||||
activeBaseRegex,
|
||||
|
@ -61,7 +64,12 @@ function NavLink({
|
|||
);
|
||||
}
|
||||
|
||||
function NavItem({items, position, className, ...props}) {
|
||||
function NavItem({
|
||||
items,
|
||||
position = DefaultNavItemPosition,
|
||||
className,
|
||||
...props
|
||||
}) {
|
||||
const navLinkClassNames = (extraClassName, isDropdownItem = false) =>
|
||||
classnames(
|
||||
{
|
||||
|
@ -147,6 +155,21 @@ function MobileNavItem({items, position, className, ...props}) {
|
|||
);
|
||||
}
|
||||
|
||||
// If split links by left/right
|
||||
// if position is unspecified, fallback to right (as v1)
|
||||
function splitLinks(links) {
|
||||
const leftLinks = links.filter(
|
||||
(linkItem) => (linkItem.position ?? DefaultNavItemPosition) === 'left',
|
||||
);
|
||||
const rightLinks = links.filter(
|
||||
(linkItem) => (linkItem.position ?? DefaultNavItemPosition) === 'right',
|
||||
);
|
||||
return {
|
||||
leftLinks,
|
||||
rightLinks,
|
||||
};
|
||||
}
|
||||
|
||||
function Navbar() {
|
||||
const {
|
||||
siteConfig: {
|
||||
|
@ -178,6 +201,8 @@ function Navbar() {
|
|||
[setLightTheme, setDarkTheme],
|
||||
);
|
||||
|
||||
const {leftLinks, rightLinks} = splitLinks(links);
|
||||
|
||||
return (
|
||||
<nav
|
||||
ref={navbarRef}
|
||||
|
@ -232,16 +257,12 @@ function Navbar() {
|
|||
</strong>
|
||||
)}
|
||||
</Link>
|
||||
{links
|
||||
.filter((linkItem) => linkItem.position === 'left')
|
||||
.map((linkItem, i) => (
|
||||
{leftLinks.map((linkItem, i) => (
|
||||
<NavItem {...linkItem} key={i} />
|
||||
))}
|
||||
</div>
|
||||
<div className="navbar__items navbar__items--right">
|
||||
{links
|
||||
.filter((linkItem) => linkItem.position === 'right')
|
||||
.map((linkItem, i) => (
|
||||
{rightLinks.map((linkItem, i) => (
|
||||
<NavItem {...linkItem} key={i} />
|
||||
))}
|
||||
{!disableDarkMode && (
|
||||
|
|
|
@ -228,15 +228,14 @@ export function createExcerpt(fileString: string): string | undefined {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
export function parse(
|
||||
fileString: string,
|
||||
): {
|
||||
type ParsedMarkdown = {
|
||||
frontMatter: {
|
||||
[key: string]: any;
|
||||
};
|
||||
content: string;
|
||||
excerpt: string | undefined;
|
||||
} {
|
||||
};
|
||||
export function parseMarkdownString(markdownString: string): ParsedMarkdown {
|
||||
const options: {} = {
|
||||
excerpt: (file: matter.GrayMatterFile<string>): void => {
|
||||
// Hacky way of stripping out import statements from the excerpt
|
||||
|
@ -246,8 +245,31 @@ export function parse(
|
|||
},
|
||||
};
|
||||
|
||||
const {data: frontMatter, content, excerpt} = matter(fileString, options);
|
||||
try {
|
||||
const {data: frontMatter, content, excerpt} = matter(
|
||||
markdownString,
|
||||
options,
|
||||
);
|
||||
return {frontMatter, content, excerpt};
|
||||
} catch (e) {
|
||||
throw new Error(`Error while parsing markdown front matter.
|
||||
This can happen if you use special characteres like : in frontmatter values (try using "" around that value)
|
||||
${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function parseMarkdownFile(
|
||||
source: string,
|
||||
): Promise<ParsedMarkdown> {
|
||||
const markdownString = await fs.readFile(source, 'utf-8');
|
||||
try {
|
||||
return parseMarkdownString(markdownString);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Error while parsing markdown file ${source}
|
||||
${e.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeUrl(rawUrls: string[]): string {
|
||||
|
|
|
@ -84,7 +84,9 @@ export function loadConfig(siteDir: string): DocusaurusConfig {
|
|||
throw new Error(
|
||||
`The field(s) ${formatFields(
|
||||
unrecognizedFields,
|
||||
)} are not recognized in ${CONFIG_FILE_NAME}`,
|
||||
)} are not recognized in ${CONFIG_FILE_NAME}.
|
||||
If you still want these fields to be in your configuration, put them in the 'customFields' attribute.
|
||||
See https://v2.docusaurus.io/docs/docusaurus.config.js/#customfields`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -11,7 +11,9 @@ This migration guide is targeted at Docusaurus users without translation and/or
|
|||
|
||||
:::
|
||||
|
||||
This doc guides you through migrating an existing Docusaurus 1 site to Docusaurus 2. Your Docusaurus 1 site should have the following structure:
|
||||
This doc guides you through migrating an existing Docusaurus 1 site to Docusaurus 2.
|
||||
|
||||
Your Docusaurus 1 site should have the following structure:
|
||||
|
||||
```sh
|
||||
├── docs
|
||||
|
@ -26,6 +28,22 @@ This doc guides you through migrating an existing Docusaurus 1 site to Docusauru
|
|||
└── static
|
||||
```
|
||||
|
||||
After the migration, your Docusaurus 2 site could look like:
|
||||
|
||||
```sh
|
||||
website
|
||||
├── blog
|
||||
├── docs
|
||||
├── src
|
||||
│ ├── components
|
||||
│ ├── css
|
||||
│ └── pages
|
||||
├── static
|
||||
├── package.json
|
||||
├── sidebars.json
|
||||
├── docusaurus.config.js
|
||||
```
|
||||
|
||||
## Project setup
|
||||
|
||||
### `package.json`
|
||||
|
@ -104,7 +122,9 @@ A typical Docusaurus 2 `package.json` may look like this:
|
|||
|
||||
### Update references to the `build` directory
|
||||
|
||||
In Docusaurus 1, all the build artifacts are located within `website/build/<PROJECT_NAME>`. However, in Docusaurus 2, it is now moved to just `website/build`. Make sure that you update your deployment configuration to read the generated files from the correct `build` directory.
|
||||
In Docusaurus 1, all the build artifacts are located within `website/build/<PROJECT_NAME>`.
|
||||
|
||||
In Docusaurus 2, it is now moved to just `website/build`. Make sure that you update your deployment configuration to read the generated files from the correct `build` directory.
|
||||
|
||||
If you are deploying to GitHub pages, make sure to run `yarn deploy` instead of `yarn publish-gh-pages` script.
|
||||
|
||||
|
@ -135,11 +155,17 @@ yarn-debug.log*
|
|||
yarn-error.log*
|
||||
```
|
||||
|
||||
### `README`
|
||||
|
||||
The D1 website may have an existing README file. You can modify it to reflect the D2 changes, or copy the default [Docusaurus v2 README](https://github.com/facebook/docusaurus/blob/master/packages/docusaurus-init/templates/classic/README.md).
|
||||
|
||||
## Site configurations
|
||||
|
||||
### `docusaurus.config.js`
|
||||
|
||||
Rename `siteConfig.js` to `docusaurus.config.js`. In Docusaurus 2, we split each functionality (blog, docs, pages) into plugins for modularity. Presets are bundles of plugins and for backward compatibility we built a `@docusaurus/preset-classic` preset which bundles most of the essential plugins present in Docusaurus 1.
|
||||
Rename `siteConfig.js` to `docusaurus.config.js`.
|
||||
|
||||
In Docusaurus 2, we split each functionality (blog, docs, pages) into plugins for modularity. Presets are bundles of plugins and for backward compatibility we built a `@docusaurus/preset-classic` preset which bundles most of the essential plugins present in Docusaurus 1.
|
||||
|
||||
Add the following preset configuration to your `docusaurus.config.js`.
|
||||
|
||||
|
@ -165,17 +191,19 @@ module.exports = {
|
|||
|
||||
We recommend moving the `docs` folder into the `website` folder and that is also the default directory structure in v2. [Now](https://zeit.co/now) supports [Docusaurus project deployments out-of-the-box](https://github.com/zeit/now-examples/tree/master/docusaurus) if the `docs` directory is within the `website`. It is also generally better for the docs to be within the website so that the docs and the rest of the website code are co-located within one `website` directory.
|
||||
|
||||
If you are migrating your Docusaurus v1 website, and there are pending documentation pull requests, you can temporarily keep the `/docs` folder to its original place, to avoid producing conflicts.
|
||||
|
||||
Refer to migration guide below for each field in `siteConfig.js`.
|
||||
|
||||
### Updated fields
|
||||
|
||||
#### `baseUrl`, `tagline`, `title`, `url`, `favicon`, `organizationName`, `projectName`, `githubHost`, `scripts`, `stylesheets`
|
||||
|
||||
No actions needed.
|
||||
No actions needed, these configuration fields were not modified.
|
||||
|
||||
#### `colors`
|
||||
|
||||
Deprecated. We wrote a custom CSS framework for Docusaurus 2 called Infima which uses CSS variables for theming. The docs are not quite ready yet and we will update here when it is. To overwrite Infima's CSS variables, create your own CSS file (e.g. `./src/css/custom.css`) and import it globally by passing it as an option to `@docusaurus/preset-classic`:
|
||||
Deprecated. We wrote a custom CSS framework for Docusaurus 2 called [Infima](https://facebookincubator.github.io/infima/) which uses CSS variables for theming. The docs are not quite ready yet and we will update here when it is. To overwrite Infima's CSS variables, create your own CSS file (e.g. `./src/css/custom.css`) and import it globally by passing it as an option to `@docusaurus/preset-classic`:
|
||||
|
||||
```js {7-9} title="docusaurus.config.js"
|
||||
module.exports = {
|
||||
|
@ -448,12 +476,74 @@ npm run swizzle @docusaurus/theme-classic Footer
|
|||
|
||||
This will copy the current `<Footer />` component used by the theme to a `src/theme/Footer` directory under the root of your site, you may then edit this component for customization.
|
||||
|
||||
Do not swizzle the Footer just to add the logo on the left. The logo is intentionally removed in v2 and moved to the bottom. Just configure the footer in `docusaurus.config.js` with `themeConfig.footer`:
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
themeConfig: {
|
||||
footer: {
|
||||
logo: {
|
||||
alt: 'Facebook Open Source Logo',
|
||||
src: 'img/oss_logo.png',
|
||||
href: 'https://opensource.facebook.com',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Pages
|
||||
|
||||
Please refer to [creating pages](creating-pages.md) to learn how Docusaurus 2 pages work. After reading that, notice that you have to move `pages/en` files in v1 to `src/pages` instead.
|
||||
|
||||
In Docusaurus v1, pages received the `siteConfig` object as props.
|
||||
|
||||
In Docusaurus v2, get the `siteConfig` object from `useDocusaurusContext` instead.
|
||||
|
||||
In v2, you have to apply the theme layout around each page. The Layout component takes metadata props (`permalink` is important, as it defines the canonical url of your page).
|
||||
|
||||
`CompLibrary` is deprecated in v2, so you have to write your own React component or use Infima styles (Docs will be available soon, sorry about that! In the meanwhile, inspect the V2 website or view https://facebookincubator.github.io/infima/ to see what styles are available).
|
||||
|
||||
You can migrate CommonJS to ES6 imports/exports.
|
||||
|
||||
Here's a typical Docusaurus v2 page:
|
||||
|
||||
```jsx
|
||||
import React from 'react';
|
||||
import Link from '@docusaurus/Link';
|
||||
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
|
||||
import useBaseUrl from '@docusaurus/useBaseUrl';
|
||||
import Layout from '@theme/Layout';
|
||||
|
||||
const MyPage = () => {
|
||||
const {siteConfig} = useDocusaurusContext();
|
||||
return (
|
||||
<Layout
|
||||
permalink="/"
|
||||
title={siteConfig.title}
|
||||
description={siteConfig.tagline}>
|
||||
<div className="hero text--center">
|
||||
<div className="container ">
|
||||
<div className="padding-vert--md">
|
||||
<h1 className="hero__title">{siteConfig.title}</h1>
|
||||
<p className="hero__subtitle">{siteConfig.tagline}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Link
|
||||
to={useBaseUrl('/docs/get-started')}
|
||||
className="button button--lg button--outline button--primary">
|
||||
Get started
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default MyPage;
|
||||
```
|
||||
|
||||
The following code could be helpful for migration of various pages:
|
||||
|
||||
- Index page - [Flux](https://github.com/facebook/flux/blob/master/website/src/pages/index.js/) (recommended), [Docusaurus 2](https://github.com/facebook/docusaurus/blob/master/website/src/pages/index.js/), [Hermes](https://github.com/facebook/hermes/blob/master/website/src/pages/index.js/)
|
||||
|
@ -469,6 +559,8 @@ This feature is deprecated. You may read more about it in [this issue](https://g
|
|||
|
||||
In Docusaurus 2, the markdown syntax has been changed to [MDX](https://mdxjs.com/). Hence there might be some broken syntax in the existing docs which you would have to update. A common example is self-closing tags like `<img>` and `<br>` which are valid in HTML would have to be explicitly closed now ( `<img/>` and `<br/>`). All tags in MDX documents have to be valid JSX.
|
||||
|
||||
Frontmatter is parsed by [gray-matter](https://github.com/jonschlinkert/gray-matter). If your frontmatter use special characters like `:`, you now need to quote it: `title: Part 1: my part1 title` -> `title: Part 1: "my part1 title"`.
|
||||
|
||||
**Tips**: You might want to use some online tools like [HTML to JSX](https://transform.tools/html-to-jsx) to make the migration easier.
|
||||
|
||||
### Language-specific code tabs
|
||||
|
@ -517,6 +609,8 @@ You might want to refer to our migration PRs for [Create React App](https://gith
|
|||
|
||||
For any questions, you can ask in the [`#docusaurus-1-to-2-migration` Discord channel](https://discordapp.com/invite/kYaNd6V). Feel free to tag [@yangshun](https://github.com/yangshun) in any migration PRs if you would like us to have a look.
|
||||
|
||||
---
|
||||
|
||||
## Versioned Site
|
||||
|
||||
:::caution
|
||||
|
@ -525,8 +619,6 @@ The versioning feature is a work in progress! Although we've implemented docs ve
|
|||
|
||||
:::
|
||||
|
||||
## Changes from v1
|
||||
|
||||
Read up https://v2.docusaurus.io/blog/2018/09/11/Towards-Docusaurus-2#versioning first for problems in v1's approach.
|
||||
|
||||
### Migrate your `versioned_docs` front matter
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue