metalsmith-sanity
📌 Simple plugin to import data from Sanity and inject it in the files
array of Metalsmith
yarn add -D metalsmith-sanity# or npm i -D metalsmith-sanity
Usage
Add the plugin to the metalsmith
instance at the highest position possible:
const Metalsmith = const metalsmithSanity = const isProduction = processenvNODE_ENV === 'production' const metalsmith = source'./source'
Quick tip
I highly encourage you to use groq.js as a means for accessing the data before passing it into templates instead of trying to process it through plain JS methods. It's going to save you tons of time and headaches 😉
Quick example:
// Inside of metalsmith.jsmetalsmith // layoutRenderer.js module { // You can set the data file key in the metalsmith-sanity plugin options const sanityData = files'sanity.json' // Example GROQ query that expands the post.category reference const postsQuery = `*[_type == 'post']{ category->{name}, ... }` // Get all the posts through groq's methods const postsTree = const allPosts = await // And finally add an html file for each post for const post of allPosts files`/index.html` = // The content comes from a postTemplate function, which could be a // nunjucks template, React / Vue / Svelte component, or much more! contents: Buffer }
If we were to go through the sanityData
array above and manually expand each post.category
reference, we'd have something like:
const allPosts = sanityData
Not too hard, right? Now imagine doing this sort of manual operations to data with 10+ types of documents and thousands of entries? Believe me, it's not fun! GROQ solves all this and more, and it's easier to learn and even more powerful than GraphQL for this sorts of operations! If in doubt, feel free to reach me on Twitter.