Fix/prettier one line import

This commit is contained in:
Igor Martyniuk
2026-07-07 09:32:10 +00:00
parent 87cfa6652b
commit 9e4f153b10
5 changed files with 82 additions and 69 deletions
@@ -0,0 +1,75 @@
const estreePlugin = require('prettier/plugins/estree');
function hasSpecifierComments(node) {
return node.specifiers?.some((specifier) => specifier.comments?.length > 0) ?? false;
}
function flattenImportLines(doc) {
if (typeof doc === 'string') {
return doc;
}
if (Array.isArray(doc)) {
return doc.map(flattenImportLines);
}
if (!doc || typeof doc !== 'object') {
return doc;
}
if (doc.type === 'line') {
return ' ';
}
if ('contents' in doc) {
return {
...doc,
contents: flattenImportLines(doc.contents)
};
}
if (doc.type === 'fill' && 'parts' in doc) {
return {
...doc,
parts: flattenImportLines(doc.parts)
};
}
if (doc.type === 'if-break') {
return {
...doc,
breakContents: flattenImportLines(doc.breakContents),
flatContents: flattenImportLines(doc.flatContents)
};
}
if (doc.type === 'group' && 'expandedStates' in doc) {
return {
...doc,
expandedStates: flattenImportLines(doc.expandedStates)
};
}
return doc;
}
const estreePrinter = estreePlugin.printers.estree;
module.exports = {
printers: {
estree: {
...estreePrinter,
print(path, options, print, args) {
const printed = estreePrinter.print(path, options, print, args);
const node = path.getNode();
if (node?.type === 'ImportDeclaration' && !hasSpecifierComments(node)) {
return flattenImportLines(printed);
}
return printed;
}
}
}
};