Nuxt Content は Nuxt.js アプリケーションでコンテンツを管理するための優れたモジュールですが、デフォルトでは現在のプロジェクト内のファイルしか参照できません。しかし、プロジェクト外のファイルを取得したいケースもあります。
今回はそんなときに cwd オプションを利用すると実現できたので利用方法をメモ📝
外部ファイルを取得するための問題
通常、Nuxt Content は content ディレクトリ内のファイルを自動的に解析して提供します。
モノレポ構成で別パッケージのドキュメントを表示したいというような外部ファイルを参照したいケースでは単純に../other_project/contentsというように辿ってもコンテンツを扱うことはできません。
解決策: cwd オプションに絶対パスを指定する
Nuxt Content の defineCollection 関数内で source オブジェクトの cwd プロパティを設定することで、ファイルの取得元ディレクトリを指定できます。Nuxt Content の公式ドキュメントにも明記されているように、cwd プロパティには必ず絶対パスを設定する必要があります。
cwd
If you want to include files from a folder outside the content directory, set the absolute path of that folder to the cwd property. https://content.nuxt.com/docs/collections/sources#cwd
サンプルコード
以下の content.config.ts は、プロジェクト外の .github フォルダ内の Markdown ファイルを取得する例です:
import { defineContentConfig, defineCollection } from "@nuxt/content"; import path from "node:path"; // 絶対パスを生成して外部ディレクトリを指定 const externalDocsPath = path.resolve("../other_project", "contents"); export default defineContentConfig({ collections: { externalDocs: defineCollection({ type: "page", source: { // cwd: 絶対パスで取得元のベースディレクトリを指定 cwd: externalDocsPath, include: "**/*.md" } }), }, });