对 TypeScript 的支持
Docusaurus is written in TypeScript and provides first-class TypeScript support.
初始化
Docusaurus 支持编写及使用采用 TypeScript 开发的主题组件。如果你选择的初始化模板提供了对 Typescript 的支持,那么你就可以通过 --typescript
标志来初始化一个完全支持 TypeScript 的站点。
npx create-docusaurus@latest my-website classic --typescript
以下是一些关于如何将现有项目迁移到 TypeScript 的指南。
安装设置
想要使用 TypeScript 开发的话,请在项目中添加 @docusaurus/module-type-aliases
插件以及一些基础的 TS 配置:
- npm
- Yarn
npm install --save-dev typescript @docusaurus/module-type-aliases @tsconfig/docusaurus
yarn add --dev typescript @docusaurus/module-type-aliases @tsconfig/docusaurus
然后在项目的根目录下添加 tsconfig.json
文件,此文件包含的内容如下:
{
"extends": "@tsconfig/docusaurus/tsconfig.json"
}
Docusaurus 在编译您的项目时并不会用到 tsconfig.json
文件。添加此文件的目的只是为了获得更好的编辑器体验(虽然您可以通过手工或在 CI 上运行 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.
我们建议使用 JSDoc 类型注释:
// @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)非常有用,可以帮助 IDE 理解配置对象(config objects)的类型!
The best IDEs (VSCode, WebStorm, IntelliJ...) will provide a nice auto-completion experience.
info
默认情况下,Docusaurus 的 TypeScript 配置并不对 JavaScript 文件做类型检查。
// @ts-check
注释可以确保在运行时对配置文件做正确的类型检查。
- npm
- Yarn
npx tsc
npx tsc
覆盖 TypeScript 编写的主题组件
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
- Yarn
npm run swizzle @docusaurus/theme-classic Footer -- --typescript
yarn 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.