Skip to content

Instantly share code, notes, and snippets.

@maxandron
Created April 23, 2023 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxandron/ce7ca54f2e808dadd209e34ebe751f92 to your computer and use it in GitHub Desktop.
Save maxandron/ce7ca54f2e808dadd209e34ebe751f92 to your computer and use it in GitHub Desktop.
A small wrapper around prettier to format (without breaking) the custom Slidev markdown
const fs = require('fs');
const prettier = require('prettier');
const START_TAG = '\n<!-- prettier-ignore-start -->\n';
const END_TAG = '\n<!-- prettier-ignore-end -->\n';
function addPrettierIgnoreTags(content) {
const pattern = /---(?:\n.+)*\n---/g;
return content.replace(pattern, (match) => {
return `${START_TAG}\n${match}\n${END_TAG}`;
});
}
function removePrettierIgnoreTags(content) {
return content.replace(new RegExp(START_TAG, 'g'), '').replace(new RegExp(END_TAG, 'g'), '');
}
function main() {
if (process.argv.length !== 3) {
console.log('Usage: node slidev-prettier.js <slides.md path>');
process.exit(1);
}
const filePath = process.argv[2];
fs.readFile(filePath, 'utf8', (err, content) => {
if (err) {
console.error(`Error reading file: ${err}`);
process.exit(1);
}
content = addPrettierIgnoreTags(content);
const formattedContent = prettier.format(content, { parser: 'markdown' });
const finalContent = removePrettierIgnoreTags(formattedContent);
fs.writeFile(filePath, finalContent, 'utf8', (err) => {
if (err) {
console.error(`Error writing file: ${err}`);
process.exit(1);
}
});
});
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment