VitePress Data Loading
VitePress provides a mechanism to load data at build time and access that data in client-side components. This is very useful for fetching data from local files (such as JSON, YAML) or remote APIs and generating static content.
This functionality is implemented by creating .data.js or .data.ts files.
Basic Usage
-
Create Data Loader File
Create a
.data.jsfile with the same name as your Markdown file anywhere in yourdocsdirectory. For example, if you have amembers.md, you can create amembers.data.js. -
Write Data Loading Script
In the
.data.jsfile, you need to export aloadfunction. This function is executed during build time in the Node.js environment.createContentLoaderis a helper function for loading and transforming a set of Markdown files. The first parameter is a glob pattern used to match the files you want to load.You can also export a custom
loadfunction to fetch data from anywhere:
Accessing Data in Components
Once you've defined the data loader file, VitePress will automatically handle data loading and passing. You can directly access this data in the .md file with the same name as the data file.
Data is exposed through the useData composable function.
In this example, members.data.js uses createContentLoader to load a series of member Markdown files. In members.md, we retrieved this member data through useData and rendered a list using v-for.
How It Works
- Build Time (Node.js): VitePress scans your files, finds all
.data.jsfiles, and executes theloadfunction in each file, serializing the returned data into JSON. - Client Side (Browser): When a user visits a page, VitePress asynchronously loads the corresponding page's data as needed. The
useDatacomposable returns this pre-loaded data.
Caching
The result of the load function will be cached. If you want to reload data every time a file changes in development mode, you can set the watch option.
Data loading is a powerful feature of VitePress that allows you to combine static content with dynamic data sources to create more complex, data-driven websites while maintaining the performance advantages of static sites.