nuxt-schema-org
Version:
The quickest and easiest way to build Schema.org graphs for Nuxt.
38 lines (37 loc) • 1.22 kB
JavaScript
import { defineWebPage } from "@unhead/schema-org/vue";
import { defu } from "defu";
import { defineNitroPlugin } from "nitropack/runtime";
import { useSchemaOrgConfig } from "../utils/config.js";
export default defineNitroPlugin((nitroApp) => {
const config = useSchemaOrgConfig();
nitroApp.hooks.hook("content:file:afterParse", async (content) => {
if (content._draft || content._extension !== "md" || content._partial || content.indexable === false || content.index === false)
return;
if (!content.schemaOrg) {
return;
}
const nodes = Array.isArray(content.schemaOrg) ? content.schemaOrg : [defineWebPage(content.schemaOrg)];
const replaceType = (node) => {
if (node.type) {
node["@type"] = node.type;
delete node.type;
}
Object.entries(node).forEach(([, value]) => {
if (typeof value === "object") {
replaceType(value);
}
});
return node;
};
const script = {
type: "application/ld+json",
key: "schema-org-graph",
nodes: nodes.map(replaceType),
...config.scriptAttributes
};
content.head = defu({
script: [script]
}, content.head);
return content;
});
});