TypeScript 支持
Docusaurus 由 TypeScript 写成,并提供一流的 TypeScript 支持。
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
To start using TypeScript, add @docusaurus/module-type-aliases
and the base TS config to your project:
- npm
- Yarn
- pnpm
npm install --save-dev typescript @docusaurus/module-type-aliases @tsconfig/docusaurus
yarn add --dev typescript @docusaurus/module-type-aliases @tsconfig/docusaurus
pnpm add --save-dev typescript @docusaurus/module-type-aliases @tsconfig/docusaurus
Then add tsconfig.json
to your project root with the following content:
{
"extends": "@tsconfig/docusaurus/tsconfig.json",
"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
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:
// @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;
类型注解非常有用,它能够帮助你的编辑器理解配置对象的类型!
The best IDEs (VS Code, WebStorm, IntelliJ...) will provide a nice auto-completion experience.
默认情况下,Docusaurus TypeScript 配置不会对 JavaScript 文件进行类型检查。
The // @ts-check
comment ensures the config file is properly type-checked when running npx tsc
.
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
- Yarn
- pnpm
npm run swizzle @docusaurus/theme-classic Footer -- --typescript
yarn swizzle @docusaurus/theme-classic Footer --typescript