入门
安装
在你的 Nuxt 应用中开始使用 Nuxt Content v3。
安装包
选择你喜欢的包管理器来安装 Nuxt Content v3:
pnpm add @nuxt/content
yarn add @nuxt/content
npm install @nuxt/content
bun add @nuxt/content
注册模块
在你的 nuxt.config.ts 文件中添加 Nuxt Content 模块:
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxt/content']
})
自动安装
使用 create-nuxt CLI 创建新 Nuxt 项目时,可以直接从交互式模块选择器中选择 @nuxt/content。这将自动为你安装并注册该模块。
npm create nuxt <project-name>
yarn create nuxt <project-name>
pnpm create nuxt <project-name>
bun create nuxt <project-name>
deno -A npm:create-nuxt@latest <project-name>
当你在 Node.js 中运行项目时,Nuxt Content 会询问你使用哪个数据库连接器。
你可以选择安装
如果你不想安装任何包,可以使用 Node.js @v22.5.0 或更新版本中的原生 SQLite。
查看
你可以选择安装
better-sqlite3 或 sqlite3 包。如果你不想安装任何包,可以使用 Node.js @v22.5.0 或更新版本中的原生 SQLite。
查看
experimental.sqliteConnector 配置。如果你使用 pnpm v10+,默认不会执行依赖的构建脚本。
由于
你可能会遇到以下错误:
解决方法是通过运行以下命令批准所需的构建脚本:或者,如果你需要无交互的设置(例如在 CI 中),
可以通过在项目根目录的你可能还需要清空 该配置创建了一个默认的 查看更多关于编写 Markdown 页面 的信息。
由于
better-sqlite3 和 sqlite3 依赖安装后运行的构建步骤来生成本地绑定文件,你可能会遇到以下错误:
Could not locate the bindings file解决方法是通过运行以下命令批准所需的构建脚本:
pnpm approve-builds
可以通过在项目根目录的
package.json 中添加如下配置,显式允许本地构建:package.json
{
"pnpm": {
"onlyBuiltDependencies": [
"better-sqlite3",
"sqlite3"
]
}
}
node_modules,或者如果初始安装没有完成构建,则显式重新构建:pnpm rebuild better-sqlite3 sqlite3
创建你的第一个集合
在项目根目录创建一个content.config.ts 文件:content.config.ts
import { defineContentConfig, defineCollection } from '@nuxt/content'
export default defineContentConfig({
collections: {
content: defineCollection({
type: 'page',
source: '**/*.md'
})
}
})
content 集合,用于处理项目 content 文件夹内的所有 Markdown 文件。你可以根据需要自定义集合配置。type: page 表示内容文件和网站页面之间是一对一的关系。创建你的第一个 Markdown 页面
在项目根目录创建content/index.md 文件:content/index.md
# 我的第一个页面
这里是一段内容。
Display Your Page
Create thepages/index.vue file and display the page content:pages/index.vue
<script setup lang="ts">
const { data: home } = await useAsyncData(() => queryCollection('content').path('/').first())
useSeoMeta({
title: home.value?.title,
description: home.value?.description
})
</script>
<template>
<ContentRenderer v-if="home" :value="home" />
<div v-else>Home not found</div>
</template>
If you install Nuxt Content in a new Nuxt project and the project does not have a
pages directory, you also need to update the app.vue file by adding the NuxtPage component to allow pages to be rendered. (If your project already has pages, you do not need to do this.)app.vue
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
That’s it! You’ve created your first Nuxt Content page.