Simple solution to clear the collections between builds for the metalsmith-collections plugin.
The metalsmith-collections plugin is a great simple way to manage the projects and blog posts on this website. It has one flaw: when rebuilding a website it does not remove the old elements in the collection(s); this creates duplicate information for each file in the collection after every re-build.
This is a simple bug and there is already a pull request that will hopefully solve the issue. Until that time, I came up with a temporary solution to remove the old elements from the collection.
The Code
Create a file named clear_collections.js
.
// clear_collections.js
module.exports = (collectionNames) => {
return function (files, metalsmith, done) {
"use strict";
let meta = metalsmith.metadata();
for (let collection of collectionNames) {
if (collection in meta) {
meta[collection] = [];
}
}
metalsmith.metadata(meta);
done();
};
};
In your build.js
file, import the clear_collections
plugin and add it to the .use()
chain before you run the metalsmith-collections plugin. Add the collection names as an option passed to the clear_collections
plugin.
// build.js
const clear_collections = require("./clear_collections");
// ...in the .use() chain
.use(clear_collections(["collection1", "etc..."]))
.use(collections(
{
collection1:"...collection1 options",
etc: "etc options..."
}
))
Restart your build process.