Using React, Typescript, Vite, Prettier.
I’m trying to customize some formatting options in Prettier, specifically have the opening curly bracket {
in functions one line below their signature like so:
function myFunc()
{
}
instead of
function myFunc() {
}
I got the following:
import { doc } from 'prettier';
import parserBabel from 'prettier/parser-babel';
function printFunctionDeclaration(path, options, print) {
const node = path.getValue();
if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
const parts = [
print(path.get("id")), // Print the function name
"(",
print(path.get("params")),
")",
];
// Add the opening curly brace on a new line
parts.push([doc.builders.line, "{"]);
// Print the body of the function
parts.push(print(path.get("body")));
return doc.builders.indent(parts);
}
return null;
}
export default {
parsers: {
astFormat: "babel",
babel: {
parse: (text, parsers, options) => {
const ast = parserBabel.parsers.babel.parse(text, parsers, options);
return ast;
},
},
},
printers: {
astFormat: "babel",
babel: {
print(path, options, print) {
const node = path.getValue();
// Check for function declaration or arrow function expression
if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
return printFunctionDeclaration(path, options, print);
}
// Default printing for other nodes
return print(path);
},
}
},
};
But after linking it to my .prettierrc
file and trying it, it gives me the following error: Error: astFormat is required.