跳到主要内容
版本:3.6.3

TypeScript 支持

Docusaurus 由 TypeScript 写成,并提供一流的 TypeScript 支持。

The minimum required version is TypeScript 5.1.

Initialization

Docusaurus 支持编写和使用 TypeScript 主题组件。 If the init template provides a TypeScript variant, you can directly initialize a site with full TypeScript support by using the --typescript flag.

npx create-docusaurus@latest my-website classic --typescript

下面是一些关于如何将现有项目迁移到 TypeScript 的指南。

Setup

将下列软件包添加到您的项目:

npm install --save-dev typescript @docusaurus/module-type-aliases @docusaurus/tsconfig @docusaurus/types

Then add tsconfig.json to your project root with the following content:

tsconfig.json
{
"extends": "@docusaurus/tsconfig",
"compilerOptions": {
"baseUrl": "."
}
}

Docusaurus doesn't use this tsconfig.json to compile your project. It is added just for a nicer Editor experience, although you can choose to run tsc to type check your code for yourself or on CI.

现在,你可以开始撰写 TypeScript 主题组件了。

Typing the config file

可以在 Docusaurus 中使用 TypeScript 配置文件。

docusaurus.config.ts
import type {Config} from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';

const config: Config = {
title: 'My Site',
favicon: 'img/favicon.ico',

/* 你的站点配置 */

presets: [
[
'classic',
{
/* 你的预设配置 */
} satisfies Preset.Options,
],
],

themeConfig: {
/* 你的主题配置 */
} satisfies Preset.ThemeConfig,
};

export default config;
It is also possible to use JSDoc type annotations within a .js file:

默认情况下,Docusaurus TypeScript 配置不会对 JavaScript 文件进行类型检查。

The // @ts-check comment ensures the config file is properly type-checked when running npx tsc.

docusaurus.config.js
// @ts-check

/** @type {import('@docusaurus/types').Config} */
const config = {
tagline: 'Dinosaurs are cool',
favicon: 'img/favicon.ico',

/* 你的站点配置 */

presets: [
[
'@docusaurus/preset-classic',
/** @type {import('@docusaurus/preset-classic').Options} */
(
{
/* 你的预设配置 */
}
),
],
],
themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
(
{
/* 你的主题配置 */
}
),
};

export default config;
提示

类型注解非常有用,它能够帮助你的编辑器理解配置对象的类型!

The best IDEs (VS Code, WebStorm, IntelliJ...) will provide a nice auto-completion experience.

Swizzling TypeScript theme components

For themes that support TypeScript theme components, you can add the --typescript flag to the end of the swizzle command to get TypeScript source code. For example, the following command will generate index.tsx and styles.module.css into src/theme/Footer.

npm run swizzle @docusaurus/theme-classic Footer -- --typescript

All official Docusaurus themes support TypeScript theme components, including theme-classic, theme-live-codeblock, and theme-search-algolia. If you are a Docusaurus theme package author who wants to add TypeScript support, see the Lifecycle APIs docs.