Command Line Interface
-
Install required packages:
We have to install the following packages:
@content-collections/core
@content-collections/cli
concurrently
pnpm add -D @content-collections/core @content-collections/cli concurrently
-
Adjust your
tsconfig.json
:{ "compilerOptions": { // ... "paths": { "content-collections": ["./.content-collections/generated"] } } }
We require a path alias for the generated files. This is necessary because the CLI will generate the files in the
.content-collections/generated
folder. -
Add the content-collection cli to your
package.json
scripts:{ "scripts": { "dev": "concurrently 'content-collections watch' 'build-scripts dev'", "build": "content-collections build && build-scripts build" } }
First, we modify the
dev
script to simultaneously execute thecontent-collections watch
command along with our regulardev
command.Next, we execute the
content-collections build
command prior to our regularbuild
command.Note: Make sure to replace
build-scripts
with the appropriate command for your framework, such asnext
orvite
. -
Create a
content-collections.ts
file at the root of your project:import { defineCollection, defineConfig } from "@content-collections/core"; const posts = defineCollection({ name: "posts", directory: "src/posts", include: "**/*.md", schema: (z) => ({ title: z.string(), summary: z.string(), }), }); export default defineConfig({ collections: [posts], });
This file defines a collection named
posts
in thesrc/posts
folder. The collection will include all markdown files (**/*.md
) and the schema will validate thetitle
andsummary
fields. -
Create your content files (e.g.:
src/posts/hello-world.md
):--- title: "Hello world" summary: "This is my first post!" --- # Hello world This is my first post! ... rest of the content
You can create unlimited content files. These files will be validated against the schema defined in the
content-collections.ts
file. If the files are valid, they will be automatically added to theposts
collection. -
Usage in your code:
import { allPosts } from "content-collections";
Now you can just import the
allPosts
collection and use it in your code. TheallPosts
collection will contain all posts that are valid. Thepost
object will contain thetitle
,summary
andcontent
fields as well as some meta information in the_meta
field.