docs(v2): more examples on lifecycle apis, cleanup (#2051)

* docs(v2): more examples on lifecycle apis, cleanup

* typo
This commit is contained in:
Endi 2019-11-26 01:31:57 +07:00 committed by Yangshun Tay
parent 085f522817
commit 91b261af7a
10 changed files with 465 additions and 436 deletions

View file

@ -73,7 +73,7 @@ export interface Props extends LoadContext {
export interface PluginContentLoadedActions {
addRoute(config: RouteConfig): void;
createData(name: string, data: Object): Promise<string>;
createData(name: string, data: any): Promise<string>;
}
export interface Plugin<T> {

View file

@ -1,310 +0,0 @@
---
id: advanced-plugins
title: Writing Plugins
---
In this doc, we talk about the design intention of plugins and how you may write your own plugins.
Docusaurus Plugins are very similar to [Gatsby Plugins](https://www.gatsbyjs.org/plugins/) and [VuePress Plugins](https://v1.vuepress.vuejs.org/plugin/). The main difference here is that Docusaurus plugins don't allow plugins to include another plugin. Docusaurus provides [presets](presets.md) to bundle plugins that are meant to work together.
## Plugins design
Docusaurus' implementation of the plugins system provides us with a convenient way to hook into the website's lifecycle to modify what goes on during development/build, which involves (but not limited to) extending the webpack config, modifying the data being loaded and creating new components to be used in a page.
## Creating plugins
A plugin is a module which exports a function that takes two parameters and returns an object when executed.
### Module definition
The exported modules for plugins are called with two parameters: `context` and `options` and returns a JavaScript object with defining the [lifecycle APIs](./lifecycle-apis.md).
```js
// Example contents of a Docusaurus plugin.
module.exports = function(context, options) {
// ...
return {
name: 'my-docusaurus-plugin',
async loadContent() { ... },
async contentLoaded({content, actions}) { ... },
/* other lifecycle api */
};
};
```
#### `context`
`context` is plugin-agnostic and the same object will be passed into all plugins used for a Docusaurus website. The `context` object contains the following fields:
```js
interface LoadContext {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
}
```
#### `options`
`options` are the [second optional parameter when the plugins are used](using-plugins.md#configuring-plugins). `options` are plugin-specific and are specified by users when they use them in `docusaurus.config.js`. Alternatively, if preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to individual plugin to define what options it takes.
#### Return value
The returned object value should implement the [lifecycle APIs](./lifecycle-apis.md).
## Official plugins
Find the list of official Docusaurus plugins [here](https://github.com/facebook/docusaurus/tree/master/packages).
### `@docusaurus/plugin-content-blog`
Provides the [Blog](blog.md) feature and is the default blog plugin for Docusaurus. The classic template ships with this plugin with default configurations.
```js
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Path to data on filesystem
* relative to site dir
*/
path: 'blog',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
postsPerPage: 10,
/**
* Theme components used by the blog pages
*/
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [],
rehypePlugins: [],
/**
* Truncate marker, can be a regex or string.
*/
truncateMarker: /<!--\s*(truncate)\s*-->/
/**
* Blog feed
* If feedOptions is undefined, no rss feed will be generated
*/
feedOptions: {
type: '', // required. 'rss' | 'feed' | 'all'
title: '', // default to siteConfig.title
description: '', // default to `${siteConfig.title} Blog`
copyright: '',
language: undefined; // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
};
},
],
],
};
```
### `@docusaurus/plugin-content-docs`
Provides the [Docs](markdown-features.mdx) functionality and is the default docs plugin for Docusaurus. The classic template ships with this plugin with default configurations.
```js
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
/**
* Path to data on filesystem
* relative to site dir
*/
path: 'docs',
/**
* URL for editing website repo, example: 'https://github.com/facebook/docusaurus/edit/master/website/'
*/
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website/',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: 'docs',
include: ['**/*.md', '**/*.mdx'], // Extensions to include.
/**
* Path to sidebar configuration for showing a list of markdown pages.
* Warning: will change
*/
sidebarPath: '',
/**
* Theme components used by the docs pages
*/
docLayoutComponent: '@theme/DocPage',
docItemComponent: '@theme/DocItem',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [],
rehypePlugins: [],
/**
* Whether to display the author who last updated the doc.
*/
showLastUpdateAuthor: false,
/**
* Whether to display the last date the doc was updated.
*/
showLastUpdateTime: false,
},
],
],
};
```
### `@docusaurus/plugin-content-pages`
The default pages plugin for Docusaurus. The classic template ships with this plugin with default configurations. This plugin provides [creating pages](creating-pages.md) functionality.
```js
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docuaurus/plugin-content-pages',
{
/**
* Path to data on filesystem
* relative to site dir
* components in this directory will be automatically converted to pages
*/
path: 'src/pages',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: '',
include: ['**/*.{js,jsx}'],
},
],
],
};
```
### `@docusaurus/plugin-google-analytics`
The default [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/) plugin.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-analytics
```
**Configuration**
```js
// docusaurus.config.js
module.exports = {
plugins: ['@docusaurus/plugin-google-analytics'],
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
},
},
};
```
### `@docusaurus/plugin-google-gtag`
The default [Global Site Tag (gtag.js)](https://developers.google.com/analytics/devguides/collection/gtagjs/) plugin.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-gtag
```
**Configuration**
```js
// docusaurus.config.js
module.exports = {
plugins: ['@docusaurus/plugin-google-gtag'],
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
},
},
};
```
### `@docusaurus/plugin-sitemap`
The classic template ships with this plugin. This plugin creates sitemap for your site so that search engine crawlers can crawl your site more accurately.
```js
// docusaurus.config.js
module.exports = {
plugins: [
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000, // 600 sec - cache purge period
changefreq: 'weekly',
priority: 0.5,
},
],
};
```
### `@docusaurus/plugin-ideal-image`
Docusaurus Plugin to generate an almost ideal image (responsive, lazy-loading, and low quality placeholder)
```bash npm2yarn
npm install --save @docusaurus/plugin-ideal-image
```
Modify your `docusaurus.config.js`
```diff
module.exports = {
...
+ plugins: ['@docusaurus/plugin-ideal-image'],
...
}
```
## Usage
This plugin supports png, gif and jpg only
```jsx
import Image from '@theme/IdealImage';
import thumbnail from './path/to/img.png';
// your react code
<Image img={thumbnail} />
// or
<Image img={require('./path/to/img.png')} />
```
### Options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | `ideal-img/[name].[hash:hex:7].[width].[ext]` | Filename template for output files. |
| `sizes` | `array` | _original size_ | Specify all widths you want to use. If a specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up).|
| `size` | `integer` | _original size_ | Specify one width you want to use; if the specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up) |
| `min` | `integer` | | As an alternative to manually specifying `sizes`, you can specify `min`, `max` and `steps`, and the sizes will be generated for you. |
| `max` | `integer` | | See `min` above |
| `steps` | `integer` | `4` | Configure the number of images generated between `min` and `max` (inclusive) |
| `quality` | `integer` | `85` | JPEG compression quality |

View file

@ -1,57 +0,0 @@
---
id: advanced-themes
title: Writing Themes
---
In this doc, we discuss how themes are designed and how you can write your own themes.
## Themes design
While themes share the exact same lifecycle methods with plugins, their implementations can look very different from those of plugins based on themes' designed objectives.
Themes are designed to complete the build of your Docusaurus site and supply the components used by your site, plugins, and the themes themselves. So a typical theme implementation would look like a `src/index.js` file that hooks it up to the lifecycle methods. Most likely they would not use `loadContent`, which plugins would use. And it is typically accompanied by a `src/theme` directory full of components.
To summarize:
- Themes share the same lifecycle methods with Plugins
- Themes are run after all existing Plugins
- Themes exist to add component aliases by extending the webpack config
## Writing customized Docusaurus themes
A Docusaurus theme normally includes an `index.js` file where you hook up to the lifecycle methods, alongside with a `theme/` directory of components. A typical Docusaurus `theme` folder looks like this:
```shell {5-7}
website
├── package.json
└── src
├── index.js
└── theme
├── MyThemeComponent
└── AnotherThemeComponent.js
```
There are two lifecycle methods that are essential to theme implementation:
- [getThemePath](lifecycle-apis.md#getthemepath)
- [getClientModules](lifecycle-apis.md#getclientmodules)
<!--
Advanced guide on:
- customizing themes
- creating your own themes
- swizzling components
Related pieces
---
- [Guides Themes](using-themes.md)
- [API - Themes](api-themes.md)
References
---
- [classic themes](packages/docusaurus-theme-classic/src/index.js)
- [using plugins doc](using-plugins.md)
- [vuepress docs on themes](https://v1.vuepress.vuejs.org/theme/)
-->

View file

@ -1,7 +1,7 @@
---
id: docusaurus-core
title: Docusaurus Client API
sidebar_title: Client API
sidebar_label: Client API
---
Docusaurus provides some API on client that can be helpful when building your site.

View file

@ -11,23 +11,44 @@ Lifecycle APIs are shared by Themes and Plugins.
Specifies the paths to watch for plugins and themes. The paths are watched by the dev server so that the plugin lifecycles are reloaded when contents in the watched paths change. Note that the plugins and themes modules are initially called with `context` and `options` from Node, which you may use to find the necessary directory information about the site.
```js
const contentPath = path.resolve(context.siteDir, options.path);
Example:
getPathsToWatch() {
const {include = []} = options;
const globPattern = include.map(pattern => `${contentPath}/${pattern}`);
return [...globPattern];
}
```js {6-8}
// docusaurus-plugin/src/index.js
const path = require('path');
module.exports = function(context, options) {
return {
name: 'docusaurus-plugin',
getPathsToWatch() {
const contentPath = path.resolve(context.siteDir, options.path);
return [`${contentPath}/**/*.{ts,tsx}`);
},
};
};
```
## async loadContent()
Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc).
Plugins should use this lifecycle to fetch from data sources (filesystem, remote API, headless CMS, etc) or doing some server processing.
For example, this plugin below return a random integer between 1 to 10 as content;
```js {6-7}
// docusaurus-plugin/src/index.js
const path = require('path');
module.exports = function(context, options) {
return {
name: 'docusaurus-plugin',
async loadContent() {
return 1 + Math.floor(Math.random() * 10);
},
};
};
```
## async contentLoaded({content, actions})
Plugins should use the data loaded in `loadContent` and construct the pages/routes that consume the loaded data.
Plugins should use the data loaded in `loadContent` and construct the pages/routes that consume the loaded data (optional).
### `content`
@ -38,35 +59,72 @@ Plugins should use the data loaded in `loadContent` and construct the pages/rout
`actions` contain two functions:
- `addRoute(config: RouteConfig): void`
- `createData(name: string, data: Object): Promise<string>`
where `RouteConfig` is an object with the necessary data to configure a route to add to the website:
Create a route to add to the website.
```js
```typescript
interface RouteConfig {
path: string;
component: string;
modules?: RouteModule;
routes?: RouteConfig[];
exact?: boolean;
priority?: number;
}
interface RouteModule {
[module: string]: Module | RouteModule | RouteModule[];
}
type Module =
| {
path: string;
__import?: boolean;
query?: ParsedUrlQueryInput;
}
| string;
```
Example `addRoute` call:
- `createData(name: string, data: any): Promise<string>`
```js
addRoute({
path: '/help',
component: '@site/src/pages/help',
exact: true,
});
A helper function to help you write some data (usually a string or JSON) to disk with in-built caching. It takes a file name relative to to your plugin's directory **(name)**, your data **(data)**, and will return a path to where the data is created.
For example, this plugin below create a `/roll` page which display "You won xxxx" to user.
```jsx
// website/src/components/roll.js
import React from 'react';
export default function(props) {
const {prizes} = props;
const index = Math.floor(Math.random() * 3);
return <div> You won ${prizes[index]} </div>;
}
```
And `createData` takes a file name relative to to your plugin's directory, a string for the `JSON.stringify` result of your data, and will return a path to the module which you may then use as the path to items in your `RouteModule`. The modules will be loaded when the related pages are loaded following our optimizations according to the [PRPL pattern](https://developers.google.com/web/fundamentals/performance/prpl-pattern/).
```javascript {5-20}
// docusaurus-plugin/src/index.js
module.exports = function(context, options) {
return {
name: 'docusaurus-plugin',
async contentLoaded({content, actions}) {
const {createData, addRoute} = actions;
// create a data named 'prizes.json'
const prizes = JSON.stringify(['$1', 'a cybertruck', 'nothing']);
const prizesDataPath = await createData('prizes.json', prizes);
// add '/roll' page using 'website/src/component/roll.js` as the component
// and providing 'prizes' as props
addRoute({
path: '/roll',
component: '@site/src/components/roll.js',
modules: {
prizes: prizesDataPath
}
exact: true,
});
},
};
};
```
## configureWebpack(config, isServer, utils)
@ -90,16 +148,23 @@ The initial call to `configureWebpack` also receives a util object consists of t
You may use them to return your webpack configures conditionally.
Example:
For example, this plugin below modify the webpack config to transpile `.foo` file.
```js
configureWebpack(config, isServer) {
if (!isServer) {
// mutate the webpack config for client
}
return config;
},
```js {5-12}
// docusaurus-plugin/src/index.js
module.exports = function(context, options, utils) {
return {
name: 'docusaurus-plugin',
configureWebpack(config, isServer) {
const {getCacheLoader} = utils;
config.modules.rules.push({
test: /\.foo$/,
use: [getCacheLoader(isServer), 'my-custom-webpack-loader'],
});
return config;
},
};
};
```
## postBuild(props)
@ -123,13 +188,19 @@ interface Props extends LoadContext {
Example:
```js
async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
// Print out to console all the rendered routes
routesPaths.map(route => {
console.log(route);
})
},
```js {5-10}
// docusaurus-plugin/src/index.js
module.exports = function(context, options, utils) {
return {
name: 'docusaurus-plugin',
async postBuild({siteConfig = {}, routesPaths = [], outDir}) {
// Print out to console all the rendered routes
routesPaths.map(route => {
console.log(route);
});
},
};
};
```
## extendCli(cli)
@ -138,15 +209,21 @@ Register an extra command to enhance the CLI of docusaurus. `cli` is [commander]
Example:
```js
extendCli(cli) {
cli
.command('roll')
.description('Roll a random number between 1 and 1000')
.action(() => {
console.log(Math.floor(Math.random() * 1000 + 1));
});
},
```js {5-12}
// docusaurus-plugin/src/index.js
module.exports = function(context, options, utils) {
return {
name: 'docusaurus-plugin',
extendCli(cli) {
cli
.command('roll')
.description('Roll a random number between 1 and 1000')
.action(() => {
console.log(Math.floor(Math.random() * 1000 + 1));
});
},
};
};
```
## getThemePath()
@ -155,7 +232,7 @@ Returns the path to the directory where the theme components can be found. When
If you use the folder directory above, your `getThemePath` can be:
```js
```js {7-9}
// my-theme/src/index.js
const path = require('path');
@ -175,7 +252,7 @@ Returns an array of paths to the modules that are to be imported in the client b
As an example, to make your theme load a `customCss` object from `options` passed in by the user:
```js
```js {8-10}
// my-theme/src/index.js
const path = require('path');

View file

@ -1,6 +1,6 @@
---
id: theme-classic
title: Classic Theme Configuration
title: "@docusaurus/theme-classic"
---
> :warning: _This section is a work in progress._

View file

@ -1,13 +1,10 @@
---
id: using-plugins
title: Plugins
sidebar_label: Introduction
---
Plugins are the building blocks of features in a Docusaurus 2 site. Each plugin handles its own individual feature. Plugins may work and be distributed as part of bundle via [presets](presets.md).
In this doc, we talk about how to use plugins with Docusaurus' official plugins. To learn about the design implementation and how to write your own plugins, check out [Advanced Guides: Plugins](advanced-plugins.md).
## Installing a plugin
A plugin is usually a npm package, so you install them like other npm packages using npm.
@ -78,3 +75,306 @@ module.exports = {
],
};
```
## Plugins design
Docusaurus' implementation of the plugins system provides us with a convenient way to hook into the website's lifecycle to modify what goes on during development/build, which involves (but not limited to) extending the webpack config, modifying the data being loaded and creating new components to be used in a page.
## Creating plugins
A plugin is a module which exports a function that takes two parameters and returns an object when executed.
### Module definition
The exported modules for plugins are called with two parameters: `context` and `options` and returns a JavaScript object with defining the [lifecycle APIs](./lifecycle-apis.md).
```js
// my-docusaurus-plugin.js
module.exports = function(context, options) {
// ...
return {
name: 'my-docusaurus-plugin',
async loadContent() { ... },
async contentLoaded({content, actions}) { ... },
/* other lifecycle api */
};
};
```
#### `context`
`context` is plugin-agnostic and the same object will be passed into all plugins used for a Docusaurus website. The `context` object contains the following fields:
```js
interface LoadContext {
siteDir: string;
generatedFilesDir: string;
siteConfig: DocusaurusConfig;
outDir: string;
baseUrl: string;
}
```
#### `options`
`options` are the [second optional parameter when the plugins are used](using-plugins.md#configuring-plugins). `options` are plugin-specific and are specified by users when they use them in `docusaurus.config.js`. Alternatively, if preset contains the plugin, the preset will then be in charge of passing the correct options into the plugin. It is up to individual plugin to define what options it takes.
#### Return value
The returned object value should implement the [lifecycle APIs](./lifecycle-apis.md).
## Official plugins
Find the list of official Docusaurus plugins [here](https://github.com/facebook/docusaurus/tree/master/packages).
### `@docusaurus/plugin-content-blog`
Provides the [Blog](blog.md) feature and is the default blog plugin for Docusaurus. The classic template ships with this plugin with default configurations.
```js
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-blog',
{
/**
* Path to data on filesystem
* relative to site dir
*/
path: 'blog',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: 'blog',
include: ['*.md', '*.mdx'],
postsPerPage: 10,
/**
* Theme components used by the blog pages
*/
blogListComponent: '@theme/BlogListPage',
blogPostComponent: '@theme/BlogPostPage',
blogTagsListComponent: '@theme/BlogTagsListPage',
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [],
rehypePlugins: [],
/**
* Truncate marker, can be a regex or string.
*/
truncateMarker: /<!--\s*(truncate)\s*-->/
/**
* Blog feed
* If feedOptions is undefined, no rss feed will be generated
*/
feedOptions: {
type: '', // required. 'rss' | 'feed' | 'all'
title: '', // default to siteConfig.title
description: '', // default to `${siteConfig.title} Blog`
copyright: '',
language: undefined; // possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
};
},
],
],
};
```
### `@docusaurus/plugin-content-docs`
Provides the [Docs](markdown-features.mdx) functionality and is the default docs plugin for Docusaurus. The classic template ships with this plugin with default configurations.
```js
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docusaurus/plugin-content-docs',
{
/**
* Path to data on filesystem
* relative to site dir
*/
path: 'docs',
/**
* URL for editing website repo, example: 'https://github.com/facebook/docusaurus/edit/master/website/'
*/
editUrl: 'https://github.com/facebook/docusaurus/edit/master/website/',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: 'docs',
include: ['**/*.md', '**/*.mdx'], // Extensions to include.
/**
* Path to sidebar configuration for showing a list of markdown pages.
* Warning: will change
*/
sidebarPath: '',
/**
* Theme components used by the docs pages
*/
docLayoutComponent: '@theme/DocPage',
docItemComponent: '@theme/DocItem',
/**
* Remark and Rehype plugins passed to MDX
*/
remarkPlugins: [],
rehypePlugins: [],
/**
* Whether to display the author who last updated the doc.
*/
showLastUpdateAuthor: false,
/**
* Whether to display the last date the doc was updated.
*/
showLastUpdateTime: false,
},
],
],
};
```
### `@docusaurus/plugin-content-pages`
The default pages plugin for Docusaurus. The classic template ships with this plugin with default configurations. This plugin provides [creating pages](creating-pages.md) functionality.
```js
// docusaurus.config.js
module.exports = {
plugins: [
[
'@docuaurus/plugin-content-pages',
{
/**
* Path to data on filesystem
* relative to site dir
* components in this directory will be automatically converted to pages
*/
path: 'src/pages',
/**
* URL route for the blog section of your site
* do not include trailing slash
*/
routeBasePath: '',
include: ['**/*.{js,jsx}'],
},
],
],
};
```
### `@docusaurus/plugin-google-analytics`
The default [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/) plugin.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-analytics
```
**Configuration**
```js
// docusaurus.config.js
module.exports = {
plugins: ['@docusaurus/plugin-google-analytics'],
themeConfig: {
googleAnalytics: {
trackingID: 'UA-141789564-1',
},
},
};
```
### `@docusaurus/plugin-google-gtag`
The default [Global Site Tag (gtag.js)](https://developers.google.com/analytics/devguides/collection/gtagjs/) plugin.
**Installation**
```bash npm2yarn
npm install --save @docusaurus/plugin-google-gtag
```
**Configuration**
```js
// docusaurus.config.js
module.exports = {
plugins: ['@docusaurus/plugin-google-gtag'],
themeConfig: {
gtag: {
trackingID: 'UA-141789564-1',
},
},
};
```
### `@docusaurus/plugin-sitemap`
The classic template ships with this plugin. This plugin creates sitemap for your site so that search engine crawlers can crawl your site more accurately.
```js
// docusaurus.config.js
module.exports = {
plugins: [
'@docusaurus/plugin-sitemap',
{
cacheTime: 600 * 1000, // 600 sec - cache purge period
changefreq: 'weekly',
priority: 0.5,
},
],
};
```
### `@docusaurus/plugin-ideal-image`
Docusaurus Plugin to generate an almost ideal image (responsive, lazy-loading, and low quality placeholder)
```bash npm2yarn
npm install --save @docusaurus/plugin-ideal-image
```
Modify your `docusaurus.config.js`
```diff
module.exports = {
...
+ plugins: ['@docusaurus/plugin-ideal-image'],
...
}
```
#### Usage
This plugin supports png, gif and jpg only
```jsx
import Image from '@theme/IdealImage';
import thumbnail from './path/to/img.png';
// your react code
<Image img={thumbnail} />
// or
<Image img={require('./path/to/img.png')} />
```
#### Options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | `ideal-img/[name].[hash:hex:7].[width].[ext]` | Filename template for output files. |
| `sizes` | `array` | _original size_ | Specify all widths you want to use. If a specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up).|
| `size` | `integer` | _original size_ | Specify one width you want to use; if the specified size exceeds the original image's width, the latter will be used (i.e. images won't be scaled up) |
| `min` | `integer` | | As an alternative to manually specifying `sizes`, you can specify `min`, `max` and `steps`, and the sizes will be generated for you. |
| `max` | `integer` | | See `min` above |
| `steps` | `integer` | `4` | Configure the number of images generated between `min` and `max` (inclusive) |
| `quality` | `integer` | `85` | JPEG compression quality |

View file

@ -1,7 +1,6 @@
---
id: using-themes
title: Themes
sidebar_label: Introduction
---
Like plugins, themes are designed to add functionality to your Docusaurus site. As a good rule of thumb, themes are mostly focused on client-side, where plugins are more focused on server-side functionalities. Themes are also designed to be replace-able with other themes.
@ -101,6 +100,37 @@ This will copy the current `<Footer />` component used by the theme to a `src/th
- [@docusaurus/theme-search-algolia](https://github.com/facebook/docusaurus/tree/master/packages/docusaurus-theme-search-algolia)
- [@docusaurus/theme-live-codeblock](https://github.com/facebook/docusaurus/tree/master/packages/docusaurus-theme-live-codeblock)
## Themes design
While themes share the exact same lifecycle methods with plugins, their implementations can look very different from those of plugins based on themes' designed objectives.
Themes are designed to complete the build of your Docusaurus site and supply the components used by your site, plugins, and the themes themselves. So a typical theme implementation would look like a `src/index.js` file that hooks it up to the lifecycle methods. Most likely they would not use `loadContent`, which plugins would use. And it is typically accompanied by a `src/theme` directory full of components.
To summarize:
- Themes share the same lifecycle methods with Plugins
- Themes are run after all existing Plugins
- Themes exist to add component aliases by extending the webpack config
## Writing customized Docusaurus themes
A Docusaurus theme normally includes an `index.js` file where you hook up to the lifecycle methods, alongside with a `theme/` directory of components. A typical Docusaurus `theme` folder looks like this:
```shell {5-7}
website
├── package.json
└── src
├── index.js
└── theme
├── MyThemeComponent
└── AnotherThemeComponent.js
```
There are two lifecycle methods that are essential to theme implementation:
- [getThemePath](lifecycle-apis.md#getthemepath)
- [getClientModules](lifecycle-apis.md#getclientmodules)
<!--
Outline

View file

@ -143,7 +143,7 @@ Should you cut a new documentation version 1.0.1? **You probably shouldn't**. 1.
### Keep the number of versions small
As a good rule of thumb, try to keep the number of your versions below 10. **It is very likely** that you will have a lot of obsolete versioned documentation that nobody even reads anymore. For example, [Jest](https://jestjs.io/versions) for example is currently in version `24.9`, and only maintains several latest documentation version with the lowest being `22.X`. Keep it small 😊
As a good rule of thumb, try to keep the number of your versions below 10. **It is very likely** that you will have a lot of obsolete versioned documentation that nobody even reads anymore. For example, [Jest](https://jestjs.io/versions) is currently in version `24.9`, and only maintains several latest documentation version with the lowest being `22.X`. Keep it small 😊
### Use absolute import within the docs

View file

@ -25,24 +25,13 @@ module.exports = {
'deployment',
'migrating-from-v1-to-v2',
],
'Advanced Guides': [
{
type: 'category',
label: 'Plugins',
items: ['using-plugins', 'advanced-plugins'],
},
{
type: 'category',
label: 'Themes',
items: ['using-themes', 'advanced-themes', 'theme-classic'],
},
'presets',
],
'Advanced Guides': ['using-plugins', 'using-themes', 'presets'],
'API Reference': [
'cli',
'docusaurus-core',
'docusaurus.config.js',
'lifecycle-apis',
'theme-classic',
],
},
};