MkDocs

GitHub概要

mkdocs/mkdocs

Project documentation with Markdown.

スター20,871
ウォッチ232
フォーク2,529
作成日:2014年1月11日
言語:Python
ライセンス:BSD 2-Clause "Simplified" License

トピックス

documentationmarkdownmkdocspythonstatic-site-generator

スター履歴

mkdocs/mkdocs Star History
データ取得日時: 2025/8/13 01:43

ドキュメント作成ツール

MkDocs

概要

MkDocsはPythonで開発されたマークダウンベースの静的サイトジェネレータです。シンプルでクリーンなドキュメントサイト構築に特化し、豊富なテーマとプラグインエコシステムを提供します。

詳細

MkDocs(エムケードックス)は2014年にTom Christieによって開発され、マークダウンベースのドキュメント作成ツールとして広く採用されています。Pythonエコシステムの一部として、pip経由で簡単にインストールでき、設定ファイル(mkdocs.yml)による直感的な設定が可能です。Material for MkDocsを筆頭とする多彩なテーマにより、美しく機能的なドキュメントサイトを構築できます。プラグインシステムにより、検索機能、国際化、API文書生成、図表作成など様々な機能を追加できます。ライブリロード機能により、開発中のリアルタイムプレビューが可能です。GitHubやGitLabとの統合により、CI/CDパイプラインでの自動デプロイメントも簡単に実現できます。ナビゲーション構造の自動生成、クロスリファレンス、目次生成などの機能により、大規模なドキュメントプロジェクトにも対応できます。2025年現在、Python、Django、FastAPI等の多くのPythonプロジェクトで標準的なドキュメントツールとして使用され、シンプルさと機能性のバランスが評価されています。カスタムテーマ開発やプラグイン作成により、特定のニーズに応じた拡張も可能です。

メリット・デメリット

メリット

  • シンプルな設定: YAML設定ファイルによる直感的なサイト構成
  • 豊富なテーマ: Material Design等の美しいテーマが多数利用可能
  • プラグインエコシステム: 検索、国際化、API文書化など多様な機能拡張
  • Pythonエコシステム: pip install一つで環境構築、Python親和性
  • ライブリロード: 開発時のリアルタイムプレビューと高速反映
  • Git統合: マークダウンファイルによるバージョン管理と協働
  • 軽量性: 高速なビルドと最小限のリソース使用

デメリット

  • Python依存: Python環境のセットアップが必要
  • 機能制限: 高度なインタラクティブ機能には限界
  • テーマ学習: カスタマイズには各テーマの仕様理解が必要
  • プラグイン互換性: プラグイン間の競合や互換性問題
  • 大規模サイト: 非常に大きなサイトでのビルド時間増加
  • デザイン制約: React/Vue等に比べたフロントエンド自由度の制限

主要リンク

書き方の例

プロジェクトの初期化

# MkDocsのインストール
pip install mkdocs

# プロジェクトの作成
mkdocs new my-project
cd my-project

# プロジェクト構造
my-project/
    mkdocs.yml    # 設定ファイル
    docs/
        index.md  # ホームページ

基本的なmkdocs.yml設定

site_name: プロジェクトドキュメント
site_url: https://example.com/docs
repo_url: https://github.com/username/project
repo_name: username/project
edit_uri: blob/main/docs/

# ナビゲーション構造
nav:
  - ホーム: index.md
  - はじめに:
    - インストール: getting-started/installation.md
    - クイックスタート: getting-started/quickstart.md
  - ユーザーガイド:
    - 基本的な使い方: user-guide/basics.md
    - 高度な機能: user-guide/advanced.md
  - API リファレンス:
    - クラス: api/classes.md
    - 関数: api/functions.md
  - 開発者ガイド:
    - コントリビューション: developers/contributing.md
    - テスト: developers/testing.md

# テーマ設定
theme:
  name: material
  palette:
    - scheme: default
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-7
        name: ダークモードに切り替え
    - scheme: slate
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-4
        name: ライトモードに切り替え
  features:
    - navigation.tabs
    - navigation.sections
    - navigation.top
    - search.highlight
    - search.suggest
    - content.tabs.link
    - content.code.annotation
    - content.code.copy
  language: ja

# マークダウン拡張
markdown_extensions:
  - pymdownx.highlight:
      anchor_linenums: true
  - pymdownx.inlinehilite
  - pymdownx.snippets
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:pymdownx.superfences.fence_code_format
  - pymdownx.tabbed:
      alternate_style: true
  - admonition
  - pymdownx.details
  - toc:
      permalink: true
  - meta
  - def_list
  - attr_list
  - md_in_html

# プラグイン
plugins:
  - search:
      lang: ja
  - mkdocstrings:
      handlers:
        python:
          options:
            docstring_style: sphinx
  - git-revision-date-localized:
      type: date
      locale: ja

# 追加CSS・JavaScript
extra_css:
  - stylesheets/extra.css

extra_javascript:
  - javascripts/extra.js

# 追加変数
extra:
  version: 1.0.0
  social:
    - icon: fontawesome/brands/github
      link: https://github.com/username/project
    - icon: fontawesome/brands/twitter
      link: https://twitter.com/username

マークダウンドキュメントの記述

---
title: API リファレンス
description: プロジェクトのAPI仕様書
---

# API リファレンス

このページでは、プロジェクトのAPIについて詳しく説明します。

## クラス

### UserManager

`UserManager`クラスは、ユーザー管理の中核となるクラスです。

```python
class UserManager:
    """ユーザー管理を行うクラス
    
    Attributes:
        users (list): ユーザーのリスト
        active_count (int): アクティブユーザー数
    """
    
    def __init__(self):
        self.users = []
        self.active_count = 0
    
    def add_user(self, user):
        """新しいユーザーを追加
        
        Args:
            user (User): 追加するユーザー
            
        Returns:
            bool: 追加に成功した場合True
        """
        if self.validate_user(user):
            self.users.append(user)
            return True
        return False

!!! note "使用上の注意" ユーザーを追加する前に、必ずvalidate_user()メソッドで検証を行ってください。

!!! warning "重要" このAPIは実験的な機能です。将来のバージョンで変更される可能性があります。

設定例

=== "Python" ```python from user_manager import UserManager

# インスタンス作成
manager = UserManager()

# ユーザー追加
user = User(name="田中太郎", email="[email protected]")
manager.add_user(user)
```

=== "YAML" yaml user_manager: max_users: 1000 validation: email_required: true name_min_length: 2

=== "JSON" json { "user_manager": { "max_users": 1000, "validation": { "email_required": true, "name_min_length": 2 } } }

フローチャート

graph TD
    A[ユーザー登録開始] --> B{入力検証}
    B -->|成功| C[ユーザー作成]
    B -->|失敗| D[エラーメッセージ表示]
    C --> E[データベース保存]
    E --> F[登録完了メール送信]
    F --> G[登録完了]
    D --> H[再入力要求]
    H --> A

関連ページ


### プラグイン設定例
```yaml
# mkdocs.yml でのプラグイン詳細設定

plugins:
  # 検索プラグイン
  - search:
      lang: ['ja', 'en']
      separator: '[\s\-\.]+'
      prebuild_index: true

  # API文書自動生成
  - mkdocstrings:
      handlers:
        python:
          paths: [src]
          options:
            docstring_style: sphinx
            show_root_heading: true
            show_source: true
            show_bases: true
            show_submodules: true

  # Git情報表示
  - git-revision-date-localized:
      type: timeago
      locale: ja
      fallback_to_build_date: true

  # サイトマップ生成
  - sitemap:
      pretty: true
      format: xml

  # 多言語対応
  - i18n:
      default_language: ja
      languages:
        ja: 日本語
        en: English
      nav_translations:
        ja:
          Home: ホーム
          About: について

  # PDF出力
  - with-pdf:
      cover_title: プロジェクトドキュメント
      cover_subtitle: バージョン 1.0
      output_path: pdf/document.pdf

  # マクロ機能
  - macros:
      include_dir: includes
      variables:
        project_version: 1.0.0
        api_base_url: https://api.example.com

カスタムテーマの作成

# setup.py - カスタムテーマパッケージ
from setuptools import setup, find_packages

setup(
    name="mkdocs-custom-theme",
    version="1.0.0",
    description="カスタムMkDocsテーマ",
    packages=find_packages(),
    include_package_data=True,
    entry_points={
        'mkdocs.themes': [
            'custom = custom_theme',
        ]
    },
    install_requires=[
        'mkdocs>=1.0'
    ],
    zip_safe=False
)
# custom_theme/mkdocs_theme.yml - テーマ設定
extends: material
vars:
  primary_color: '#2196F3'
  accent_color: '#FF9800'
  font_family: '"Noto Sans JP", sans-serif'
  show_sidebar: true
  enable_search: true
<!-- custom_theme/main.html - メインテンプレート -->
{%- extends "base.html" %}

{% block site_meta %}
  {{ super() }}
  <meta name="author" content="{{ config.site_author }}">
  <meta property="og:image" content="{{ config.site_url }}{{ config.theme.logo }}">
{% endblock %}

{% block content %}
  {{ super() }}
  
  {% if page.meta.api %}
    <div class="api-badge">
      <span>API ドキュメント</span>
    </div>
  {% endif %}
{% endblock %}

{% block footer %}
  <footer class="md-footer">
    <div class="md-footer-meta md-typeset">
      <div class="md-footer-meta__inner md-grid">
        <div class="md-footer-copyright">
          <div class="md-footer-copyright__highlight">
            © {{ config.copyright }}
          </div>
          最終更新: {% if page.meta.git_revision_date_localized %}
            {{ page.meta.git_revision_date_localized }}
          {% endif %}
        </div>
      </div>
    </div>
  </footer>
{% endblock %}

自動デプロイ設定

# .github/workflows/docs.yml - GitHub Actions
name: Build and Deploy Documentation

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: 3.x

      - name: Cache dependencies
        uses: actions/cache@v3
        with:
          key: ${{ github.ref }}
          path: .cache

      - name: Install dependencies
        run: |
          pip install -r requirements.txt

      - name: Build documentation
        run: |
          mkdocs build --strict

      - name: Deploy to GitHub Pages
        if: github.ref == 'refs/heads/main'
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./site

開発ワークフロー

# 開発サーバーの起動
mkdocs serve

# 特定ポートでの起動
mkdocs serve --dev-addr localhost:8080

# 本番ビルド
mkdocs build

# サイトの検証
mkdocs build --strict

# クリーンビルド
mkdocs build --clean

# プラグインのデバッグ
mkdocs serve --verbose

# 設定ファイルの検証
python -m mkdocs config

プラグイン開発例

# mkdocs_plugin_example.py
from mkdocs.plugins import BasePlugin
from mkdocs.config import config_options

class ExamplePlugin(BasePlugin):
    config_scheme = (
        ('enabled', config_options.Type(bool, default=True)),
        ('prefix', config_options.Type(str, default='例:')),
    )
    
    def on_page_markdown(self, markdown, page, config, files):
        if not self.config['enabled']:
            return markdown
            
        # マークダウンの変換処理
        if page.title:
            prefix = self.config['prefix']
            markdown = f"{prefix} {markdown}"
            
        return markdown
        
    def on_page_content(self, html, page, config, files):
        # HTMLの後処理
        if 'api' in page.meta:
            html = f'<div class="api-content">{html}</div>'
        return html