Closed LukasMurdock closed 2 years ago
Copying from the unified plugin example and the .children.unshift from rehype-mdx-title I was able to add the filename with the code below. Not sure if this is an optimal solution—if this issue is outside the scope of this plugin feel free to close.
// rehype-mdx-filename.js
export function rehypeMdxFilename({ name = 'filename' } = {}) {
return transformer;
function transformer(tree, file) {
const filepath = file.history[0].replace(file.cwd, '');
tree.children.unshift({
type: 'mdxjsEsm',
data: {
estree: {
type: 'Program',
sourceType: 'module',
body: [
{
type: 'ExportNamedDeclaration',
source: null,
specifiers: [],
declaration: {
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: { type: 'Identifier', name },
init: {
type: 'Literal',
filepath,
raw: JSON.stringify(filepath),
},
},
],
},
},
],
},
},
});
}
}
Thanks for the suggestion, but I think this is out of scope of this plugin. Feel free to create your own plugin though!
Just a small tip: You can use file.basename
or file.stem
to access the filename from the VFile instance.
Looking to use the filename as title.
Would it make sense to provide an option to use the filename as default title instead of the header? Or would this be better accomplished through a different plugin?