徒然
つれづれなるままに、日暮らし

Nuxt Content v2でカスタムコードブロックを設定する

Nuxt3Nuxt Content
制作日: 2024年04月05日
カスタムコードブロック

Nuxt Content v2について

Nuxt Contentは、プロジェクト内のコンテンツ/ディレクトリを読み取り、.md.yml.csv.jsonファイルを解析して、アプリケーション用の強力なデータレイヤーを作成。
MDC構文を使用してMarkdownでVueコンポーネントを使用。

実装内容

以下のようにmdを記述する。

```cs [test.cs]
namespace Test
{
    class test
    {
        static void Main(string[] args)
        {
            Console.WriteLine("HelloWorld.");
        }
    }
}
```

以下のように表示される。

test.cs
namespace Test
{
    class test
    {
        static void Main(string[] args)
        {
            Console.WriteLine("HelloWorld.");
        }
    }
}

Proseコンポーネント

Prose Componentsは、components/content/に同じ名前のコンポーネントを作成することで、コンポーネントをオーバーライドできる。 
ex)components/content/ProseA.vue

今回はnuxt/content/ProseにあるProseCode.vueをオーバーライドする。

./components/content/ProseCode.vue
<template>
  <div class="code-container" @mouseover="onHover(true)" @mouseleave="onHover(false)">
    <div class="copy-container" v-show="isHovered">
      <span class="copied-text" v-if="copied">コピーしました</span>
      <button class="copy-button" @click="copy(code)"></button>
    </div>
    <span v-if="filename" class="filename-text">
        {{ filename }}
    </span>
    <div class="code-inner">
      <slot />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useClipboard } from '@vueuse/core';
import { ref } from 'vue';

const props = withDefaults(
    defineProps < {
        code?: string
        language?: string | null
        filename?: string | null
    } > (),{code: '', language: null, filename: null}
)

const isHovered = ref(false)
function onHover(state: boolean) {
  isHovered.value = state
}

const { copy, copied } = useClipboard();

const onClick = () => {
  copy(props.code)
}
</script>

Nuxt Content V2ではシンタックスハイライターにShikiを採用している。

テーマはtm-themesの中から選択できる。

デフォルトではjsonjstscssshellhtmlmdyamlのみハイライトされるので、必要な言語は別途nuxt.configに追加する。

nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  content: {
    highlight: {
      theme: {
        default: 'nord'
      },
      langs: [
        'cs',
        'js',
        'ts',
        'shell',
        'json',
        'html',
        'css',
        'yaml',
      ]
    }
  },
})
  • このサイトについて
  • プライバシーポリシー
Copyright© 徒然. All Rights Reserved.
徒然