跳转至主内容
Version: 2.0.0-beta.8

TypeScript 支持

Docusaurus is written in TypeScript, and provides first-class TypeScript support.

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.

npm init [email protected] my-website classic -- --typescript

Below are some guides on how to migrate an existing project to TypeScript.

设置

To start using TypeScript, add @docusaurus/module-type-aliases and the base TS config to your project:

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

随后将以下内容添加到您的项目根目录的 tsconfig.json

tsconfig.json
{
"extends": "@tsconfig/docusaurus/tsconfig.json",
"include": ["src/"]
}

Docusaurus 不会使用此 tsconfig.json 来编译您的项目。 这只是为了改善您的编辑体验,虽然您也可以选择自己或在持续集成上运行 tsc 来类型检查您的代码。

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

Typing the config file

It is not possible to use a TypeScript config file in Docusaurus, unless you compile it yourself to JavaScript.

We recommend using JSDoc type annotations:

docusaurus.config.js
// @ts-check

/** @type {import('@docusaurus/types').Plugin} */
function MyPlugin(context, options) {
return {
name: 'my-plugin',
};
}

/** @type {import('@docusaurus/types').Config} */
const config = {
title: 'Docusaurus',
tagline: 'Build optimized websites quickly, focus on your content',
organizationName: 'facebook',
projectName: 'docusaurus',
plugins: [MyPlugin],
presets: [
[
'@docusaurus/preset-classic',
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: {
path: 'docs',
sidebarPath: 'sidebars.js',
},
blog: {
path: 'blog',
postsPerPage: 5,
},
}),
],
],
themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
({
colorMode: {
defaultMode: 'dark',
},
navbar: {
hideOnScroll: true,
title: 'Docusaurus',
logo: {
alt: 'Docusaurus Logo',
src: 'img/docusaurus.svg',
srcDark: 'img/docusaurus_keytar.svg',
},
},
}),
};

module.exports = config;
tip

Type annotations are very useful and help your IDE understand the type of config objects!

The best IDEs (VSCode, WebStorm, Intellij...) will provide a nice auto-completion experience.

信息

By default, the Docusaurus TypeScript config does not type-check JavaScript files.

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

npm run tsc

变换 TypeScript 主题组件

对于支持 TypeScript 的主题组件,您可于变换(Swizzling)命令末尾添加 --typescript 参数以获取 TypeScript 源代码。 举个例子,下列代码将生成 index.tsxstyles.module.csssrc/theme/Footer

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

迄今为止,支持 TypeScript 主题组件的唯一 Docusaurus 官方主题是 @docusaurus/theme-classic。 如果您是一位 Docusaurus 主题作者,且想要添加 TypeScript 支持,请参阅生命周期 API 文档