-
-
Save ryanflorence/ec1849c6d690cfbffcb408ecd633e069 to your computer and use it in GitHub Desktop.
import type { V2_HtmlMetaDescriptor, V2_MetaFunction } from "@remix-run/node"; | |
export const mergeMeta = ( | |
overrideFn: V2_MetaFunction, | |
appendFn?: V2_MetaFunction, | |
): V2_MetaFunction => { | |
return arg => { | |
// get meta from parent routes | |
let mergedMeta = arg.matches.reduce((acc, match) => { | |
return acc.concat(match.meta || []); | |
}, [] as V2_HtmlMetaDescriptor[]); | |
// replace any parent meta with the same name or property with the override | |
let overrides = overrideFn(arg); | |
for (let override of overrides) { | |
let index = mergedMeta.findIndex( | |
meta => | |
("name" in meta && | |
"name" in override && | |
meta.name === override.name) || | |
("property" in meta && | |
"property" in override && | |
meta.property === override.property) || | |
("title" in meta && "title" in override), | |
); | |
if (index !== -1) { | |
mergedMeta.splice(index, 1, override); | |
} | |
} | |
// append any additional meta | |
if (appendFn) { | |
mergedMeta = mergedMeta.concat(appendFn(arg)); | |
} | |
return mergedMeta; | |
}; | |
}; |
import { mergeMeta } from "./merge-meta"; | |
export const meta = mergeMeta( | |
// these will override the parent meta | |
({ data }) => { | |
return [{ title: data.project.name }]; | |
}, | |
// these will be appended to the parent meta | |
({ matches }) => { | |
return [{ name: "author", content: "Ryan Florence" }]; | |
}, | |
); | |
// both functions get the same arguments as a normal meta function |
Thank you for your code @cairin, it works great, however it seems like you've forgotten about
('script:ld+json' in meta && 'script:ld+json' in parentMeta)
, since it's a possibility for merging too.
You wouldn't want to deduplicate scripts like that, because that would deduplicate different scripts too. You would need to do a full object comparison. It's probably more useful for you to add that code yourself based on your specific requirements.
You also shouldn't need to install the same script in multiple routes anyway, as long as it's installed in a route somewhere above the current route it should still be usable on the leaf route.
@cairin since TS 5.5 mergeMeta
cannot infer data
correctly.
@cairin since TS 5.5
mergeMeta
cannot inferdata
correctly.
It appears that the issue is unique to my project. I upgraded TypeScript to version 5.5.2 in a newly installed Remix app without any problems. However, comparing both tsconfig files hasn't resolved the issue. @cairin mergeMeta
function version works with latest Remix app and TS. 🤷♂️
@ryanflorence how about merge handle, does the same logic work too?
Thank you for your code @cairin, it works great, however it seems like you've forgotten about
('script:ld+json' in meta && 'script:ld+json' in parentMeta)
, since it's a possibility for merging too.