Skip to main content

TypeScript サポート

DocusaurusはTypeScriptで書かれており、最上級クラスのTypeScriptサポートを提供します。

最小必須バージョンはTypeScript 5.1です。

初期設定

Docusaurus は TypeScript を使ったテーマコンポーネントの作成とその使用をサポートしています。 初期設定用テンプレートが TypeScript 版を提供している場合、--typescript フラグを使用することで TypeScript に完全対応したサイトの初期設定ができます。

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

以下は、既存のプロジェクトを TypeScript に移行する方法についてのガイドです。

セットアップ

プロジェクトに次のパッケージを追加してください。

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

次に、tsconfig.jsonをプロジェクトのルートに以下の内容で追加してください。

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

Docusaurusはプロジェクトをコンパイルするためにこのtsconfig.jsonを使用しません。 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 のテーマコンポーネントを書き始めることができます。

設定ファイルを入力する

It is possible to use a TypeScript config file in Docusaurus.

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',

/* Your site config here */

presets: [
[
'classic',
{
/* Your preset config here */
} satisfies Preset.Options,
],
],

themeConfig: {
/* Your theme config here */
} 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',

/* Your site config here */

presets: [
[
'@docusaurus/preset-classic',
/** @type {import('@docusaurus/preset-classic').Options} */
(
{
/* Your preset config here */
}
),
],
],
themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
(
{
/* Your theme config here */
}
),
};

export default config;
ヒント

型注釈は非常に便利で、IDE が設定オブジェクトの型を理解するのに役立ちます。

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

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 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.