Prettier 3.6: ¡CLI experimental rápida y nuevos plugins para OXC y Hermes!
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Esta versión incluye varias adiciones de características importantes que nos entusiasma compartir con ustedes.
En primer lugar, estamos lanzando una nueva CLI experimental de alto rendimiento detrás de una bandera de característica (--experimental-cli). Esta CLI anteriormente solo estaba disponible en prettier@next, pero ahora puedes activarla simplemente usando una bandera. ¡Te animamos a probarla y compartir tus comentarios! Si te interesa la implementación interna, por favor lee Prettier's CLI: Análisis profundo de rendimiento por Fabio.
Adicionalmente, estamos lanzando dos nuevos plugins oficiales: @prettier/plugin-oxc y @prettier/plugin-hermes. Estos plugins se proporcionan por separado del núcleo de Prettier.
Queremos expresar nuestro más sincero agradecimiento a todos quienes hicieron posible esta increíble versión: @fabiospampinato, @43081j y @pralkarz junto con los nuevos contribuidores de la CLI, @boshen y @overlookmotel junto con otros contribuidores de OXC, los equipos de Flow y Hermes en Meta. ¡Gracias a todos por sus increíbles contribuciones!
Estamos emocionados de ver cómo estas nuevas características mejoran tu experiencia de desarrollo. ¡Feliz formateo!
Destacados
CLI
Soporte para CLI experimental (#17151, #17396 por @fisker)
Quizás ya hayas escuchado o usado nuestra nueva CLI con rendimiento mejorado. A partir de Prettier 3.6, ahora puedes usarla sin instalar la versión inestable v4.
# Run CLI with `--experimental-cli`
prettier . --check --experimental-cli
# Or use environment variable `PRETTIER_EXPERIMENTAL_CLI=1`
PRETTIER_EXPERIMENTAL_CLI=1 prettier . --check
JavaScript
Se agregó un nuevo plugin oficial @prettier/plugin-oxc (#17472, #17483 por @fisker)
@prettier/plugin-oxc está basado en OXC (un analizador rápido de JavaScript y TypeScript en Rust).
Este plugin incluye dos nuevos analizadores: oxc (sintaxis de JavaScript) y oxc-ts (sintaxis de TypeScript). Para usar este plugin:
-
Instala el plugin
yarn add --dev prettier @prettier/plugin-oxc -
Agrega lo siguiente a tu archivo
.prettierrcplugins:
- "@prettier/plugin-oxc"
Debido a limitaciones de tamaño de paquete, este plugin no está incluido en el paquete prettier y debe instalarse por separado.
Para más información, consulta la página de inicio del paquete.
Muchas gracias al equipo de OXC (@boshen, @overlookmotel y otros contribuidores).
Flow
Nuevo plugin oficial @prettier/plugin-hermes (#17520 por @fisker)
@prettier/plugin-hermes está basado en Hermes JS Engine.
Este plugin incluye un nuevo parser hermes (sintaxis Flow). Para usarlo:
-
Instala el plugin
yarn add --dev prettier @prettier/plugin-hermes -
Añade lo siguiente a tu archivo
.prettierrcplugins:
- "@prettier/plugin-hermes"
Debido a limitaciones de tamaño de paquete, este plugin no está incluido en el paquete prettier y debe instalarse por separado.
Planeamos convertirlo en el parser predeterminado para sintaxis Flow en v4, y eliminaremos el parser babel-flow en v4. ¡Por favor pruébalo!
Para más información, consulta la página del paquete.
Muchas gracias al equipo de Hermes.
Otros cambios
JavaScript
Añadir paréntesis a SequenceExpression en ReturnStatement y ExpressionStatement (#17085 por @TYKevin)
// Input
function a() {
return ( a, b)
}
(a(), b());
// Prettier 3.5
function a() {
return a, b;
}
a(), b();
// Prettier 3.6
function a() {
return (a, b);
}
(a(), b());
Añadir paréntesis a AssignmentExpression en claves de propiedades de clase (#17145 por @fisker)
Anteriormente solo añadíamos paréntesis a AssignmentExpression en claves de objetos, no en propiedades de clase. Gracias a Biome por señalar esta inconsistencia.
// Input
a = {
[(x = "key")]: 1,
}
class A {
[(x = "property")] = 1;
[(x = "method")]() {}
}
// Prettier 3.5
a = {
[(x = "key")]: 1,
};
class A {
[x = "property"] = 1;
[(x = "method")]() {}
}
// Prettier 3.6
a = {
[(x = "key")]: 1,
};
class A {
[(x = "property")] = 1;
[(x = "method")]() {}
}
Añadir paréntesis a números en expresiones de miembro opcionales (#17190 por @fisker)
Existía una inconsistencia al formatear expresiones de miembro donde el objeto era un número antes de Prettier 3.6.
Al usar el parser babel (y otros parsers basados en Babel), imprimíamos el número sin paréntesis; con el parser typescript (y otros parsers ESTree), lo imprimíamos entre paréntesis.
Técnicamente los paréntesis no son necesarios, pero si imprimimos 1?.toString() y luego los usuarios ven que no es necesario usar ?., no pueden simplemente eliminar el signo de interrogación porque 1.toString() produciría un SyntaxError. Por ello, decidimos siempre añadir paréntesis.
// Input
(1)?.toString();
(1.5)?.toString();
// Prettier 3.5 (--parser=babel)
1?.toString();
1.5?.toString();
// Prettier 3.5 (--parser=typescript)
(1)?.toString();
(1.5)?.toString();
// Prettier 3.6
(1)?.toString();
(1.5)?.toString();
Eliminado soporte para Records & Tuples experimental (#17363 por @fisker)
La propuesta ES JavaScript Records & Tuples Proposal ha sido retirada.
Preservar espacios entre palabras CSS y expresiones incrustadas (#17398 por @sosukesuzuki)
// Input
const Heading = styled.h1`
font-size: var(--font-size-h${level});
`;
// Prettier 3.5
const Heading = styled.h1`
font-size: var(--font-size-h ${level});
`;
// Prettier 3.6
const Heading = styled.h1`
font-size: var(--font-size-h${level});
`;
Corrección del formato inconsistente en asignaciones (#17469 por @fisker)
// Input
didScheduleRenderPhaseUpdateDuringThisPassFoo = didScheduleRenderPhaseUpdate = true
// Prettier 3.5 (--parser=babel)
didScheduleRenderPhaseUpdateDuringThisPassFoo =
didScheduleRenderPhaseUpdate = true;
// Prettier 3.5 (--parser=typescript)
didScheduleRenderPhaseUpdateDuringThisPassFoo = didScheduleRenderPhaseUpdate =
true;
// Prettier 3.6
didScheduleRenderPhaseUpdateDuringThisPassFoo =
didScheduleRenderPhaseUpdate = true;
Corrección del formato inconsistente en cadenas de miembros (#17470 por @fisker)
// Input
s.get(u)?.trigger({ triggerKind: y.SignatureHelpTriggerKind.InvokeFooBarBaz123 });
// Prettier 3.5 (--parser=babel)
s.get(u)?.trigger({
triggerKind: y.SignatureHelpTriggerKind.InvokeFooBarBaz123,
});
// Prettier 3.5 (--parser=typescript)
s
.get(u)
?.trigger({ triggerKind: y.SignatureHelpTriggerKind.InvokeFooBarBaz123 });
// Prettier 3.6
s.get(u)?.trigger({
triggerKind: y.SignatureHelpTriggerKind.InvokeFooBarBaz123,
});
Corrección del encadenamiento opcional como clave computada (#17486 por @fisker)
// Input
const a = { [y?.z]() {} };
class A { [y?.z]() {} };
// Prettier 3.5
const a = { [y?.z]?() {} };
class A {
[y?.z]?() {}
}
// Prettier 3.6
const a = { [y?.z]() {} };
class A {
[y?.z]() {}
}
Soporte para comentarios de conversión de tipos en los parsers acorn y meriyah (#17491, #17566 por @ArnaudBarre, #17600 por #fisker)
Esta funcionalidad solo estaba disponible anteriormente en el parser de Babel.
// Input
/** @type {MyType} */ (x).foo;
// Prettier 3.5 (--parser=acorn|meriyah)
/** @type {MyType} */ x.foo;
// Prettier 3.6
/** @type {MyType} */ (x).foo;
Corrección del formato inestable de comentarios en literales de plantilla etiquetados (#17510 por @fisker)
// Input
foo
// Comment
`x`
// Prettier 3.5 (First format)
foo// Comment
`x`;
// Prettier 3.5 (Second format)
foo // Comment
`x`;
// Prettier 3.6
foo // Comment
`x`;
Mejora de la consistencia para JSX en llamadas a métodos opcionales (#17616 por @seiyab)
// Input
<SuspendyTree>
<div style={{ height: 200, overflow: "scroll" }}>
{Array(20)
.fill()
?.map((_, i) => (
<h2 key={i}>{i + 1}</h2>
))}
</div>
</SuspendyTree>;
// Prettier 3.5 (ESTree based parsers like espree and typescript)
<SuspendyTree>
<div style={{ height: 200, overflow: "scroll" }}>
{Array(20)
.fill()
?.map((_, i) => <h2 key={i}>{i + 1}</h2>)}
</div>
</SuspendyTree>;
// Prettier 3.5 (babel and babel-ts parser)
<SuspendyTree>
<div style={{ height: 200, overflow: "scroll" }}>
{Array(20)
.fill()
?.map((_, i) => (
<h2 key={i}>{i + 1}</h2>
))}
</div>
</SuspendyTree>;
// Prettier 3.6 (parsers of both types)
<SuspendyTree>
<div style={{ height: 200, overflow: "scroll" }}>
{Array(20)
.fill()
?.map((_, i) => (
<h2 key={i}>{i + 1}</h2>
))}
</div>
</SuspendyTree>;
TypeScript
Soporte para atributos de tipo importación en TSImportType (#16881 por @fisker)
// Input
type A = import("foo", {with: {type: "json"}})
// Prettier 3.5
type A = import("foo")
// Prettier 3.6
type A = import("foo", { with: { type: "json" } });
Corrección de comentarios en expresiones lógicas y tipos de intersección (#17193 por @fisker)
// Input
export type ErrorLike =
SerializedProps<Error> &
// cause is a new addition to Error that is not yet available in all runtimes. We have added
// it to try and pinpoint additional reasoning for failures such as Node's fetch.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
{ cause?: unknown };
// Prettier 3.5
export type ErrorLike =
SerializedProps<Error> & // cause is a new addition to Error that is not yet available in all runtimes. We have added
// it to try and pinpoint additional reasoning for failures such as Node's fetch.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
{ cause?: unknown };
// Prettier 3.5 (second format)
export type ErrorLike =
SerializedProps<Error> & // it to try and pinpoint additional reasoning for failures such as Node's fetch. // cause is a new addition to Error that is not yet available in all runtimes. We have added
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
{ cause?: unknown };
// Prettier 3.6
export type ErrorLike = SerializedProps<Error> &
// cause is a new addition to Error that is not yet available in all runtimes. We have added
// it to try and pinpoint additional reasoning for failures such as Node's fetch.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
{ cause?: unknown };
Mejora en la detección de nuevas líneas en tipos mapeados (#17498 por @fisker)
// Input
type A = { readonly
[A in B]: T}
// Prettier 3.5
type A = {
readonly [A in B]: T;
};
// Prettier 3.6
type A = { readonly [A in B]: T };
Eliminación de punto y coma adicional después de firmas de índice ignoradas con prettier-ignore (#17538 por @sosukesuzuki)
// Input
type foo = {
// prettier-ignore
[key: string]: bar;
};
// Prettier 3.5
type foo = {
// prettier-ignore
[key: string]: bar;;
};
// Prettier 3.6
type foo = {
// prettier-ignore
[key: string]: bar;
};
Flow
Corrección de paréntesis faltantes en ConditionalTypeAnnotation (#17196 por @fisker)
// Input
type T<U> = 'a' | ('b' extends U ? 'c' : empty);
type T<U> = 'a' & ('b' extends U ? 'c' : empty);
// Prettier 3.5
type T<U> = "a" | "b" extends U ? "c" : empty;
type T<U> = "a" & "b" extends U ? "c" : empty;
// Prettier 3.6
type T<U> = "a" | ("b" extends U ? "c" : empty);
type T<U> = "a" & ("b" extends U ? "c" : empty);
JSON
Permitir formato en archivos JSONC que solo contienen comentarios (#17269 por @fisker)
// Input
// Comment
// Prettier 3.5
SyntaxError: Unexpected token (1:11)
> 1 | // Comment
| ^
// Prettier 3.6
// Comment
Prohibición de expresiones entre paréntesis (#17598 por @fisker)
// Input
[1, (2)]
// Prettier 3.5
[1, 2]
// Prettier 3.6
SyntaxError: 'ParenthesizedExpression' is not allowed in JSON. (1:5)
> 1 | [1, (2)]
| ^^^
CSS
Soporte para la directiva @utility en Tailwind (#17362 por @sosukesuzuki)
Este cambio añade soporte para la directiva @utility en Tailwind CSS V4.
/* Input */
@utility tab-* {
tab-size: --value(--tab-size-*);
}
/* Prettier 3.5 */
@utility tab-* {
tab-size: --value(--tab-size- *);
}
/* Prettier 3.6 */
@utility tab-* {
tab-size: --value(--tab-size-*);
}
Eliminar sangría adicional para la pseudo llamada :has (#17541 por @sosukesuzuki)
/* Input */
li:has(
path[d="M544,272H480V150.627L523.314,107.314A16,16,0,0,0,500.686,84.687L457.373,128H415a127.00381,127.00381,0,1,0-254,0H118.627L75.314,84.687A16,16,0,1,0,52.686,107.314L96,150.627V272H32a16,16,0,0,0,0,32H96v24a174.98856,174.98856,0,0,0,30.484,98.889L68.687,484.686a15.99972,15.99972,0,1,0,22.627,22.627l55.616-55.616A175.45165,175.45165,0,0,0,272,504h32a175.45165,175.45165,0,0,0,125.07-52.303l55.616,55.616a15.99972,15.99972,0,0,0,22.627-22.627l-57.797-57.797A174.98856,174.98856,0,0,0,480,328V304h64a16,16,0,0,0,0-32ZM288,32.01263A95.99568,95.99568,0,0,1,383,128H193A95.99568,95.99568,0,0,1,288,32.01263ZM448,328c0,79.401-64.598,144-144,144V236a12.00052,12.00052,0,0,0-12-12h-8a12.00052,12.00052,0,0,0-12,12V472c-79.402,0-144-64.599-144-144V160H448Z"]
) {
display: none;
}
/* Prettier 3.5 */
li:has(
path[d="M544,272H480V150.627L523.314,107.314A16,16,0,0,0,500.686,84.687L457.373,128H415a127.00381,127.00381,0,1,0-254,0H118.627L75.314,84.687A16,16,0,1,0,52.686,107.314L96,150.627V272H32a16,16,0,0,0,0,32H96v24a174.98856,174.98856,0,0,0,30.484,98.889L68.687,484.686a15.99972,15.99972,0,1,0,22.627,22.627l55.616-55.616A175.45165,175.45165,0,0,0,272,504h32a175.45165,175.45165,0,0,0,125.07-52.303l55.616,55.616a15.99972,15.99972,0,0,0,22.627-22.627l-57.797-57.797A174.98856,174.98856,0,0,0,480,328V304h64a16,16,0,0,0,0-32ZM288,32.01263A95.99568,95.99568,0,0,1,383,128H193A95.99568,95.99568,0,0,1,288,32.01263ZM448,328c0,79.401-64.598,144-144,144V236a12.00052,12.00052,0,0,0-12-12h-8a12.00052,12.00052,0,0,0-12,12V472c-79.402,0-144-64.599-144-144V160H448Z"]
) {
display: none;
}
/* Prettier 3.6 */
li:has(
path[d="M544,272H480V150.627L523.314,107.314A16,16,0,0,0,500.686,84.687L457.373,128H415a127.00381,127.00381,0,1,0-254,0H118.627L75.314,84.687A16,16,0,1,0,52.686,107.314L96,150.627V272H32a16,16,0,0,0,0,32H96v24a174.98856,174.98856,0,0,0,30.484,98.889L68.687,484.686a15.99972,15.99972,0,1,0,22.627,22.627l55.616-55.616A175.45165,175.45165,0,0,0,272,504h32a175.45165,175.45165,0,0,0,125.07-52.303l55.616,55.616a15.99972,15.99972,0,0,0,22.627-22.627l-57.797-57.797A174.98856,174.98856,0,0,0,480,328V304h64a16,16,0,0,0,0-32ZM288,32.01263A95.99568,95.99568,0,0,1,383,128H193A95.99568,95.99568,0,0,1,288,32.01263ZM448,328c0,79.401-64.598,144-144,144V236a12.00052,12.00052,0,0,0-12-12h-8a12.00052,12.00052,0,0,0-12,12V472c-79.402,0-144-64.599-144-144V160H448Z"]
) {
display: none;
}
Less
Corregir argumento de función en minúsculas incorrectamente (#17502 por @fisker)
// Input
.what {
.make-modifier(1A, "1a.png");
.make-modifier(AA, "1a.png");
}
// Prettier 3.5
.what {
.make-modifier(1a, "1a.png");
.make-modifier(AA, "1a.png");
}
// Prettier 3.6
.what {
.make-modifier(1A, "1a.png");
.make-modifier(AA, "1a.png");
}
HTML
Corregir formato cuando el nombre de etiqueta es una propiedad prototipo de objeto (#17501 por @fisker)
<!-- Input -->
<constructor>
text
</constructor>
<!-- Prettier 3.5 -->
TypeError: Vn(...).startsWith is not a function
<!-- Prettier 3.6 -->
<constructor> text </constructor>
Angular
Compatibilidad con TemplateLiteral introducido en Angular 19.2 (#17238 por @fisker)
Angular 19.2 añadió compatibilidad con TemplateLiteral.
<!-- Input -->
<div>{{ `Hello, ${
getName('world')}` }}</div>
<!-- Prettier 3.5 -->
<div>
{{ `Hello, ${
getName('world')}` }}
</div>
<!-- Prettier 3.6 -->
<div>{{ `Hello, ${getName("world")}` }}</div>
Eliminar dos puntos adicionales después de track en control-flow @for de Angular (#17280 por @claudio-herger)
// Input
@for (item of items; let i = $index; let count = $count; track block) {}
// Prettier 3.5
@for (item of items; let i = $index; let count = $count; track: block) {}
// Prettier 3.6
@for (item of items; let i = $index; let count = $count; track block) {}
Compatibilidad con Angular 20 (#17534 por @fisker)
// Input
{{
( (a in (b)))
}}
{{
( (tag ` a ${ b } \u0063 `))
}}
{{
( (` a ${ b } \u0063 `))
}}
{{ void(1 + 2) }}
// Prettier 3.5
The new syntax is not correctly recognized.
// Prettier 3.6
{{ a in b }}
{{ tag` a ${b} \u0063 ` }}
{{ ` a ${b} \u0063 ` }}
{{ void (1 + 2) }}
MJML
Habilitar formato CSS dentro de la etiqueta <mj-style> (#17338 por @iryusa)
<!-- Input -->
<mj-style>
.hello {
color: blue;
border: 1px solid blue;
font-size:12px;
} p { font-size: 14px; }
</mj-style>
<!-- Prettier 3.5 -->
<mj-style>
.hello { color: blue; border: 1px solid blue; font-size:12px; } p { font-size:
14px; }
</mj-style>
<!-- Prettier 3.6 -->
<mj-style>
.hello {
color: blue;
border: 1px solid blue;
font-size: 12px;
}
p {
font-size: 14px;
}
</mj-style>
Analizar correctamente <mj-style> y <mj-raw> (#17400 por @fisker)
<!-- Input -->
<mj-style>
a::before {
content: "</p>";
}
</mj-style>
<!-- Prettier 3.5 -->
SyntaxError: Unexpected closing tag "p".
<!-- Prettier 3.6 -->
Correctly parsed as CSS.
Markdown
Corregir sintaxis markdown adyacente en blockquote (#16596 por @fiji-flo)
<!-- Input -->
> `x`
> `y`
> _x_
> _y_
> [foo](http://foo)
> [bar](http://bar)
> `this` behaves
> `correctly`
<!-- Prettier 3.5 -->
> `x` > `y`
> _x_ > _y_
> [foo](http://foo) > [bar](http://bar)
> `this` behaves `correctly`
<!-- Prettier 3.6 -->
> `x` `y`
> _x_ _y_
> [foo](http://foo) [bar](http://bar)
> `this` behaves `correctly`
Corregir inserción inesperada de nueva línea en listas de markdown (#16637 por @byplayer)
<!-- Input -->
- Level 1
- Level 1-1
- Level 2
<!-- Prettier 3.5 -->
- Level 1
- Level 1-1
- Level 2
<!-- Prettier 3.6 -->
- Level 1
- Level 1-1
- Level 2
Corregir énfasis fuerte (#17143 por @fiji-flo)
La mayoría de implementaciones de markdown no admiten 1**_2_**3, por lo que se prefiere 1***2***3.
<!-- Input -->
1***2***3
1**_2_**3
<!-- Prettier 3.5 -->
1**_2_**3
1**_2_**3
<!-- Prettier 3.6 -->
1***2***3
1***2***3
YAML
No añadir salto de línea antes de mapas o secuencias vacías (#16074 por @BapRx)
# Input
---
myDict: {}
# comment
myList: []
# comment
# Prettier 3.5
---
myDict:
{}
# comment
myList:
[]
# comment
# Prettier 3.6
---
myDict: {}
# comment
myList: []
# comment
API
Aceptar URL en la opción plugins (#17166 por @fisker)
La opción plugins ahora acepta URL con protocolo file: o cadenas URL que comienzan con file: en todas las API públicas.
// `URL`
await prettier.check("foo", {
parser: "my-cool-parser",
plugins: [new URL("./path/to/plugin.js", import.meta.url)],
});
await prettier.format("foo", {
parser: "my-cool-parser",
plugins: [new URL("./path/to/plugin.js", import.meta.url)],
});
await prettier.formatWithCursor("foo", {
parser: "my-cool-parser",
cursorOffset: 2,
plugins: [new URL("./path/to/plugin.js", import.meta.url)],
});
await prettier.getFileInfo("/path/to/file", {
plugins: [new URL("./path/to/plugin.js", import.meta.url)],
});
await prettier.getSupportInfo({
plugins: [new URL("./path/to/plugin.js", import.meta.url)],
});
// URL string
await prettier.check("foo", {
parser: "my-cool-parser",
plugins: ["file:///path/to/plugin.js"],
});
await prettier.format("foo", {
parser: "my-cool-parser",
plugins: ["file:///path/to/plugin.js"],
});
await prettier.formatWithCursor("foo", {
parser: "my-cool-parser",
cursorOffset: 2,
plugins: ["file:///path/to/plugin.js"],
});
await prettier.getFileInfo("/path/to/file", {
plugins: ["file:///path/to/plugin.js"],
});
await prettier.getSupportInfo({
plugins: ["file:///path/to/plugin.js"],
});
Aceptar URL como archivo de configuración personalizado en resolveConfig (#17167 por @fisker)
prettier.resolveConfig() ahora acepta una URL con protocolo file: o una cadena de URL que comience con file: como ubicación de archivo de configuración personalizada.
// `URL`
await prettier.resolveConfig("path/to/file", {
config: new URL("/path/to/prettier-config-file", import.meta.url),
});
// URL string
await prettier.resolveConfig("path/to/file", {
config: "file:///path/to/prettier-config-file",
});
Dejar de interpretar archivos *.frag como archivos JavaScript (#17178 por @fisker)
Los archivos *.frag se interpretaban como JavaScript, pero .frag también se usa en GLSL (Lenguaje de Sombreado OpenGL). Esto causaba errores cuando Prettier intentaba formatearlos como archivos JavaScript.
A partir de Prettier 3.6, los archivos *.frag excepto *.start.frag, *.end.frag, start.frag y end.frag ya no se tratan como archivos JavaScript.
Si tienes archivos JavaScript con extensión .frag que no coinciden con los patrones mencionados anteriormente, puedes configurarlo mediante overrides.
export default {
overrides: {
files: "**/*.frag",
options: {
parser: "babel",
},
},
};
Añadir soporte para la función isSupported en la API languages (#17331 por @JounQin, #17490 por @fisker)
Anteriormente, la API languages para plugins personalizados solo admitía inferir el parser basándose en el nombre base o la extensión del archivo.
Prettier 3.6 añadió la función isSupported: (options: { filepath: string }) => boolean para permitir que los plugins verifiquen si un archivo es compatible según la ruta completa (ej: archivos en un directorio específico).
Prettier no puede garantizar que filepath exista en el disco.
Cuando se usa desde APIs (ej: prettier.format()), Prettier tampoco puede garantizar que sea una ruta válida.
Si no se proporciona isSupported, el comportamiento será el mismo que antes.
export const languages = [
{
name: "foo",
parsers: ["foo"],
isSupported: ({ filepath }) => filepath.includes(".foo"),
},
];
Añadir parser mjml (#17339 por @fisker)
Ya soportábamos MJML en versiones anteriores con el parser html. Para distinguir características específicas de MJML, se añadió un nuevo parser mjml.
Ignorar archivos con --check-ignore-pragma (#17344 por @wnayes)
Ahora los archivos individuales pueden excluirse del formateo mediante comentarios "pragma" @noformat o @noprettier en la parte superior del archivo.
Para habilitar esta función, usa la nueva opción --check-ignore-pragma (checkIgnorePragma mediante configuración o API).
Los plugins de lenguaje pueden implementar soporte para esta función. La mayoría de los parsers integrados, incluyendo JavaScript (TypeScript), CSS, HTML, JSON, Markdown (MDX), YAML y GraphQL, se actualizaron para soportar esta función.
/**
* @noformat
*/
export default matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
);
Corrección de carga de plugins en prettier.getFileInfo() (#17548 por @fisker)
En versiones anteriores, prettier.getFileInfo() solo leía la configuración parser de .prettierrc, pero no cargaba plugins para inferir el parser a partir de los languages del plugin. Prettier 3.6 corrige este comportamiento.
// prettier-plugin-foo
export const languages = [
{
parsers: ["foo"],
extensions: [".foo"],
},
];
# .prettierrc
plugins:
- prettier-plugin-foo
prettier --file-info file.foo
# Prettier 3.5
{ "ignored": false, "inferredParser": null }
# Prettier 3.6
{ "ignored": false, "inferredParser": "foo" }
Permitir que los plugins sobrescriban parsers incorporados al inferir el parser (#17549 por @fisker)
Anteriormente, al inferir el parser para un archivo, primero se verificaban los plugins incorporados, por lo que los plugins externos no podían sobrescribir parsers para archivos como .js.
// prettier-plugin-foo
export const languages = [
{
parsers: ["foo"],
extensions: [".js"],
},
];
// prettier.config.js
import * as prettierPluginFoo from "prettier-plugin-foo";
export default {
plugins: [prettierPluginFoo],
};
prettier --file-info file.js
# Prettier 3.5
{ "ignored": false, "inferredParser": "babel" }
# Prettier 3.6
{ "ignored": false, "inferredParser": "foo" }
CLI
Prohibir el uso conjunto de --config y --no-config (#12221 por @Balastrong)
$ prettier --config=.prettierrc --no-config .
[error] Cannot use --no-config and --config together.
Ignorar la hora de modificación del archivo cuando --cache-strategy=content (#17438 por @fisker)
En versiones anteriores, al usar --cache-strategy=content, si cambiaba la hora de modificación del archivo, este se volvía a formatear incluso cuando el contenido no había cambiado. Prettier 3.6 corrige este comportamiento.
Corrección del mensaje de resultado para archivos que no se pueden formatear (#17505 por @fisker)
touch unknown
prettier --check unknown
# Prettier 3.5
Checking formatting...
unknown
[error] No parser could be inferred for file "</path/to/unknown>".
All matched files use Prettier code style!
# Prettier 3.6
Checking formatting...
unknown
[error] No parser could be inferred for file "</path/to/unknown>".
Error occurred when checking code style in the above file.
Corrección del exitCode cuando el parser no puede inferir (#17505 por @fisker)
touch unknown
prettier --check unknown > /dev/null;echo $?
# Prettier 3.5
[error] No parser could be inferred for file "</path/to/unknown>".
0
# Prettier 3.6
[error] No parser could be inferred for file "</path/to/unknown>".
2
Varios
Corrección del formato incrustado con cursorOffset (#17254 por @fisker)
<!-- Input (--cursor-offset=1) -->
# Angular note
```typescript
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
imports: [],
template: `
<h1>
{{ title }}</h1>
`,
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'default';
}
```
<!-- Prettier 3.5 -->
Error: There are too many 'cursor' in doc.
<!-- Prettier 3.6 -->
# Angular note
```typescript
import { Component } from "@angular/core";
@Component({
selector: "app-root",
standalone: true,
imports: [],
template: `
<h1>
{{ title }}
</h1>
`,
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "default";
}
```
