Prettier 2.2: nuevos parsers JavaScript, soporte para TS 4.1 y bundles ESM independientes
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 soporte para los nuevos parsers JavaScript espree y meriyah, compatibilidad con TypeScript 4.1, bundles ESM independientes para navegadores modernos, además de muchas correcciones de errores y mejoras!
Destacados
JavaScript
Adición de los parsers espree y meriyah (#9000, #9514 por @fisker)
Se han añadido dos nuevos valores para la opción parser:
-
espree- parser predeterminado deESLint.Nota:
espreesolo funciona con Propuestas ECMAScript Finalizadas y es más estricto que el parserbabel.
TypeScript
Soporte para TypeScript 4.1 (#9473, #9636 por @sosukesuzuki)
Reasignación de claves en tipos mapeados
// Input
type MappedTypeWithNewKeys<T> = {
[K in keyof T as NewKeyType]: T[K]
};
// Prettier 2.1
SyntaxError: Unexpected token, expected "]" (2:17)
1 | type MappedTypeWithNewKeys<T> = {
> 2 | [K in keyof T as NewKeyType]: T[K]
| ^
3 | };
// Prettier 2.2
type MappedTypeWithNewKeys<T> = {
[K in keyof T as NewKeyType]: T[K]
};
Tipos de literales de plantilla
// Input
type HelloWorld = `Hello, ${keyof World}`
// Prettier 2.1
SyntaxError: Unexpected token, expected "}" (1:35)
> 1 | type HelloWorld = `Hello, ${keyof World}`
| ^
// Prettier 2.2
type HelloWorld = `Hello, ${keyof World}`;
API
Bundles ESM independientes (#8983 por @Monchi, @fisker)
Prettier ahora también incluye módulos ES, que pueden usarse directamente en navegadores modernos:
import prettier from "https://unpkg.com/prettier/esm/standalone.mjs";
import parserGraphql from "https://unpkg.com/prettier/esm/parser-graphql.mjs";
prettier.format("query { }", {
parser: "graphql",
plugins: [parserGraphql],
});
Otros cambios
JavaScript
Respetar espaciado entre valores de plantilla en CSS embebido (#9078 por @sosukesuzuki)
// Input
const style = css`
width: ${size}${sizeUnit};
`;
// Prettier 2.1
const style = css`
width: ${size} ${sizeUnit};
`;
// Prettier 2.2
const style = css`
width: ${size}${sizeUnit};
`;
Corregir comentarios dentro de literales de plantilla con sintaxis embebida (#9278 por @fisker)
// Input
html`${
foo
/* comment */
}`;
html`
${
foo
/* comment */
}
`;
graphql`${
foo
/* comment */
}`;
css`${
foo
/* comment */
}`;
// Prettier 2.1
html`${foo}`;
/* comment */
html`
${foo}
/* comment */
`;
graphql`
${foo}
/* comment */
`;
css`
${foo}
/* comment */
`;
// Prettier 2.2
html`${
foo
/* comment */
}`;
html`
${
foo
/* comment */
}
`;
graphql`${
foo
/* comment */
}`;
css`${
foo
/* comment */
}`;
Mejorar formato en asignaciones de clases con nombres de superclases largos (#9341 por @sosukesuzuki)
Esto mejora el formato para espacios de nombres de Google Closure Library.
// Input
aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = class extends (
aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg1
) {
method () {
console.log("foo");
}
};
// Prettier 2.1
aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = class extends aaaaaaaa
.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg1 {
method() {
console.log("foo");
}
};
// Prettier 2.2
aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg2 = class extends (
aaaaaaaa.bbbbbbbb.cccccccc.dddddddd.eeeeeeee.ffffffff.gggggggg1
) {
method() {
console.log("foo");
}
};
Corregir posición de comentarios iniciales en cuerpos de sentencias while (#9345 por @sosukesuzuki)
// Input
while(1) // Comment
foo();
// Prettier 2.1
while (
1 // Comment
)
foo();
// Prettier 2.2
while (1)
// Comment
foo();
Actualización a @babel/parser 7.12 (#9408, #9476, #9597 por @sosukesuzuki)
Se actualizó el parser de JavaScript a @babel/parser 7.12. Esto soluciona varios errores y agrega soporte para nueva sintaxis.
Soporte para Assertions de Importación
La propuesta "module attributes" soportada en 2.1 ha cambiado significativamente y ahora se renombró a "import assertions".
import foo from "./foo.json" assert { type: "json" };
Soporte para imports y exports con nombres de cadena
let happy = "happy";
export { happy as "😃" };
Soporte para bloques estáticos de clases
class C {
static #x = 42;
static y;
static {
try {
this.y = doSomethingWith(this.#x);
} catch {
this.y = "unknown";
}
}
}
Conservar literales de plantilla inválidos en HTML y Markdown tal cual (#9431 por @fisker)
// Input
foo = html`<div>\u{prettier}</div>`;
foo = html`\u{prettier}${foo}pr\u{0065}ttier`;
foo = markdown`# \u{prettier}\u{0065}`;
// Prettier 2.1
foo = html``;
foo = html`null${foo}prettier`;
foo = markdown`
# \u{prettier}\u{0065}
`;
// Prettier 2.2
foo = html`<div>\u{prettier}</div>`;
foo = html`\u{prettier}${foo}pr\u{0065}ttier`;
foo = markdown`# \u{prettier}\u{0065}`;
Corregir formato para import {a as a} y export {a as a} (#9435 por @fisker)
// Input
import { a as a } from "a";
export { b as b } from "b";
// Prettier 2.1
import { a } from "a";
export { b } from "b";
// Prettier 2.2
import { a as a } from "a";
export { b as b } from "b";
Corregir formato de expresiones JSX en yield (#9650 por @brainkim)
// Input
function* f() {
yield <div>generator</div>
}
// Prettier 2.1
function* f() {
yield (<div>generator</div>);
}
// Prettier 2.2
function* f() {
yield <div>generator</div>;
}
Aplanar parámetros de expresiones de función en el último argumento "abrazado" (#9662 por @thorn0)
// Prettier 2.1
function* mySagas() {
yield effects.takeEvery(rexpress.actionTypes.REQUEST_START, function* ({
id
}) {
console.log(id);
yield rexpress.actions(store).writeHead(id, 400);
yield rexpress.actions(store).end(id, "pong");
console.log("pong");
});
}
// Prettier 2.2
function* mySagas() {
yield effects.takeEvery(
rexpress.actionTypes.REQUEST_START,
function* ({ id }) {
console.log(id);
yield rexpress.actions(store).writeHead(id, 400);
yield rexpress.actions(store).end(id, "pong");
console.log("pong");
}
);
}
Corregir fallo en require(/* comment */) (#9670 por @fisker)
// Input
require(/* comment */)
// Prettier 2.1
Error: Comment "comment" was not printed. Please report this error!
// Prettier 2.2
require(/* comment */);
TypeScript
Conservar el último separador en tipos de objeto e interfaces ignoradas (#9318 por @sosukesuzuki)
// Input
let x: {
// prettier-ignore
y: z;
};
// Prettier 2.1
let x: {
// prettier-ignore
y: z;;
};
// Prettier 2.2
let x: {
// prettier-ignore
y: z;
};
Agregar paréntesis alrededor de asignaciones en propiedades de objetos literales (#9484 por @fisker)
// Input
foo = { bar: (a = b) };
// Prettier 2.1
foo = { bar: a = b };
// Prettier 2.2
foo = { bar: (a = b) };
Corregir inconsistencias en formato de tipos entre typescript y flow (#9521 por @fisker)
// Input
const name: SomeGeneric<
Pick<Config, "ONE_LONG_PROP" | "ANOTHER_LONG_PROP">
> = null;
// Prettier 2.1 (--parser=typescript)
const name: SomeGeneric<Pick<
Config,
"ONE_LONG_PROP" | "ANOTHER_LONG_PROP"
>> = null;
// Prettier 2.1 (--parser=flow)
const name: SomeGeneric<
Pick<Config, "ONE_LONG_PROP" | "ANOTHER_LONG_PROP">
> = null;
// Prettier 2.2 (typescript and flow parser)
const name: SomeGeneric<
Pick<Config, "ONE_LONG_PROP" | "ANOTHER_LONG_PROP">
> = null;
Corregir tipos mapeados con prettier-ignore (#9551 por @fisker)
// Input
type a= {
// prettier-ignore
[A in B]: C | D
}
// Prettier 2.1
type a = {
// prettier-ignore
A in B: C | D;
};
// Prettier 2.2
type a = {
// prettier-ignore
[A in B]: C | D
};
Flow
Cambiar el parser babel a babel-flow si se encuentra el pragma @flow (#9071 por @fisker)
En la práctica, esto significa que mientras tus archivos Flow tengan el pragma, es seguro usar la extensión .js para ellos. Prettier los analizará e imprimirá correctamente sin configuración adicional. Anteriormente, el parser reconocía el pragma pero existían problemas menores de corrección en la impresión. Por ejemplo, no es seguro quitar las comillas de claves numéricas en Flow.
// Input (with --parser babel)
// @flow
f<T>({ "2": 2 })
// Prettier 2.1
// @flow
f<T>({ 2: 2 });
// Prettier 2.2
// @flow
f<T>({ "2": 2 });
Enumeraciones con miembros desconocidos (#9432 by @gkz)
Anteriormente no estaban soportadas. Ahora se formatea lo siguiente:
// Input
enum E {
A,
B,
...
}
// Prettier 2.1: parse error
// Prettier 2.2
enum E {
A,
B,
...
}
Anotaciones de parámetros this (#9457 by @dsainati1, #9489 by @fisker)
// Input
function f(this: string, a: number) {
}
type T = (this: boolean, a: number) => boolean;
// Prettier 2.1
function f(this: string, a: number) {}
type T = (a: number) => boolean;
// Prettier 2.2
function f(this: string, a: number) {
}
type T = (this: boolean, a: number) => boolean;
Soporte para BigIntLiteralTypeAnnotation y BigIntTypeAnnotation (#9523 by @fisker)
Se añade soporte para BigIntLiteralTypeAnnotation y BigIntTypeAnnotation en Flow.
// Input
const foo: bigint = 1n;
const bar: baz<1n> = 1n;
// Prettier 2.1
Error: unknown type: "BigIntTypeAnnotation"
at ...
// Prettier 2.2
const foo: bigint = 1n;
const bar: baz<1n> = 1n;
Tratar más tipos simples como no rompibles en anotaciones de tipos genéricos (#9543 by @fisker)
// Input
const foo1: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<symbol> = a
const foo2: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<"STRING"> = a;
const foo3: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<0> = a;
// Prettier 2.1
const foo1: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<
symbol
> = a;
const foo2: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<
"STRING"
> = a;
const foo3: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<
0
> = a;
// Prettier 2.2 (typescript and flow parser)
const foo1: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<symbol> = a
const foo2: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<"STRING"> = a;
const foo3: Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo<0> = a;
Corregir paréntesis faltantes en aserciones de tipo ignoradas con prettier-ignore (#9553 by @fisker)
// Input
transform(
// prettier-ignore
(pointTransformer: (Point => Point))
);
// Prettier 2.1
transform(
// prettier-ignore
pointTransformer: (Point => Point)
);
// Prettier 2.2
transform(
// prettier-ignore
(pointTransformer: (Point => Point))
);
Mejorar detección de tipos de comentarios (#9563 by @fisker)
// Input
foo/*::<bar>*/(baz);
class Foo {
bar( data: Array<string>) {}
}
// Prettier 2.1
foo/*:: <bar> */(baz);
class Foo {
bar(data: Array/*:: <string> */) {}
}
// Prettier 2.2
foo/*:: <bar> */(baz);
class Foo {
bar(data: Array<string>) {}
}
Less
Corregir comentarios en listas de valores (#9356 by @thorn0)
// Input
@test-space-separated: #aaaaaa // Start with A
#bbbbbb // then some B
#cccccc; // and round it out with C
// Prettier 2.1
@test-space-separated: #aaaaaa a // Start with
#bbbbbb b // then some
#cccccc; // and round it out with C
// Prettier 2.2
@test-space-separated: #aaaaaa // Start with A
#bbbbbb // then some B
#cccccc; // and round it out with C
HTML
Corregir fallo al leer Node.sourceSpan (#9368 by @fisker)
<!-- Input -->
<strong>a</strong>-<strong>b</strong>-
<!-- Prettier 2.1 -->
TypeError: Cannot read property 'line' of undefined
at forceNextEmptyLine ...
<!-- Prettier 2.2 -->
<strong>a</strong>-<strong>b</strong>-
Vue
Corregir formato inconsistente para v-for (#9225 by @zweimach)
<!-- Input -->
<template>
<div
v-for="({ longLongProp=42, anotherLongLongProp='Hello, World!' }, index) of longLongLongLongLongLongLongLongList"
></div>
<div
v-for="({firstValue, secondValue, thirdValue, fourthValue, fifthValue, sixthValue}, objectKey, index) in objectWithAVeryVeryVeryVeryLongName"
></div>
</template>
<!-- Prettier 2.1 -->
<template>
<div
v-for="({ longLongProp = 42, anotherLongLongProp = 'Hello, World!' },
index) of longLongLongLongLongLongLongLongList"
></div>
<div
v-for="({
firstValue,
secondValue,
thirdValue,
fourthValue,
fifthValue,
sixthValue,
},
objectKey,
index) in objectWithAVeryVeryVeryVeryLongName"
></div>
</template>
<!-- Prettier 2.2 -->
<template>
<div
v-for="(
{ longLongProp = 42, anotherLongLongProp = 'Hello, World!' }, index
) of longLongLongLongLongLongLongLongList"
></div>
<div
v-for="(
{
firstValue,
secondValue,
thirdValue,
fourthValue,
fifthValue,
sixthValue,
},
objectKey,
index
) in objectWithAVeryVeryVeryVeryLongName"
></div>
</template>
Corregir formato inconsistente para slots, soportar script[setup] y style[vars] de Vue 3 (#9609 by @fisker)
<!-- Input -->
<script setup="props, {emit }"></script>
<style vars="{color }"></style>
<template>
<div>
<div v-slot="{destructuring:{ a:{b}}}"/>
<div v-slot:name="{destructuring:{ a:{b}}}"/>
<div #default="{destructuring:{ a:{b}}}"/>
<slot slot-scope="{destructuring:{ a:{b}}}"/>
</div>
</template>
<!-- Prettier 2.1 -->
<script setup="props, {emit }"></script>
<style vars="{color }"></style>
<template>
<div>
<div v-slot="{ destructuring: { a: { b } } }" />
<div v-slot:name="{ destructuring: { a: { b } } }" />
<div #default="{ destructuring: { a: { b } } }" />
<slot
slot-scope="{
destructuring: {
a: { b },
},
}"
/>
</div>
</template>
<!-- Prettier 2.2 -->
<script setup="props, { emit }"></script>
<style vars="{ color }"></style>
<template>
<div>
<div
v-slot="{
destructuring: {
a: { b },
},
}"
/>
<div
v-slot:name="{
destructuring: {
a: { b },
},
}"
/>
<div
#default="{
destructuring: {
a: { b },
},
}"
/>
<slot
slot-scope="{
destructuring: {
a: { b },
},
}"
/>
</div>
</template>
Handlebars (alfa)
Corregir saltos de línea inestables después de <Textarea /> (#9403 by @fisker, correcciones en simple-html-tokenizer por @rwjblue)
Markdown
Actualizar remark-math a 3.0.1; escapar signos de dólar solo si originalmente escapados (#7938 by @fisker y @thorn0)
<!-- Input -->
Paragraph with $14 million.
Paragraph with $14 million. But if more $dollars on the same line...
<!-- Prettier 2.1 -->
Paragraph with \$14 million.
Paragraph with $14 million. But if more $dollars on the same line...
<!-- Prettier 2.2 -->
Paragraph with $14 million.
Paragraph with $14 million. But if more $dollars on the same line...
Corregir líneas en blanco faltantes en bloques de código con cercado que carecen de la cerca de cierre (#8786 by @fisker)
require("prettier").format("```a\n\n\n\n", { parser: "markdown" });
<!-- Prettier 2.1 -->
'```a\n\n```\n'
<!-- Prettier 2.2 -->
'```a\n\n\n\n```\n'
Agregar soporte para enlaces [[wiki-style]] (#9275 por @iamrecursion)
-
El soporte para enlaces
[[wiki-style]]garantiza que no se rompan al formatear con Prettier mediante saltos de línea. -
El contenido del enlace (entre los corchetes
[[]]) se trata como texto sin formato. Esto se debe a que las diversas herramientas que dependen de la sintaxis[[]]no concuerdan sobre lo que es válido entre ellos.
<!-- Input -->
If I have a prose that forces a wiki link to end up crossing the [[line width limit]] like this. It's wrapped into an invalid state.
<!-- Prettier 2.1 -->
If I have a prose that forces a wiki link to end up crossing the [[line width
limit]] like this. It's wrapped into an invalid state.
<!-- Prettier 2.2 -->
If I have a prose that forces a wiki link to end up crossing the
[[line width limit]] like this. It's wrapped into an invalid state.
Alinear detección de lenguaje en bloques de código con otras herramientas populares (#9365 por @kachkaev)
Desde Prettier 1.12, los bloques de código que comienzan como ```js {something=something} se detectan como JavaScript y se formatean.
En ese entonces, pocas herramientas separaban el lenguaje de los metadatos, por lo que se decidió hacer opcional el espacio en blanco y así detectar ```js{something=something} también como JavaScript.
Con el lanzamiento de Remark v8 (utilizado por Prettier), la detección y formateo de bloques de código se volvió inconsistente en varios casos excepcionales. Además, se observó que el comportamiento de Prettier no coincidía con el resaltado de sintaxis en VSCode. Para fomentar la coherencia entre herramientas y alinearse mejor con la especificación Commonmark, ahora es obligatorio usar espacio en blanco entre el lenguaje y los metadatos.
<!-- Input -->
```js {something=something}
console.log ( "hello world" );
```
```js{something=something}
console.log ( "hello world" );
```
<!-- Prettier 2.1 -->
```js {something=something}
console.log("hello world");
```
```js{something=something}
console.log("hello world");
```
<!-- Prettier 2.2 -->
```js {something=something}
console.log("hello world");
```
```js{something=something}
console.log ( "hello world" );
```
Corregir línea vacía adicional después de tabla vacía (#9654 por @fisker)
<!-- Input -->
Test line 1
| Specify the selected option : | Option 1 |
| ----------------------------- | -------- |
Test line 6
<!-- Prettier 2.1 -->
Test line 1
| Specify the selected option : | Option 1 |
| ----------------------------- | -------- |
Test line 6
<!-- Prettier 2.2 -->
Test line 1
| Specify the selected option : | Option 1 |
| ----------------------------- | -------- |
Test line 6
MDX
Corregir líneas vacías adicionales en JSX (#9267 por @fisker)
<!-- Input -->
# title
<Jsx>
text
</Jsx>
<!-- Prettier 2.1 -->
# title
<Jsx>
text
</Jsx>
(Extra empty lines added after `<Jsx>` and `</Jsx>`)
<!-- Prettier 2.2 -->
# title
<Jsx>
text
</Jsx>
YAML
Aplicar opción trailingComma (#9665 por @fisker)
Cuando --trailing-comma=none, no debe agregar coma final en flowMapping y flowSequence.
# Input
flow-mapping:
{
"object-does-not-fit-within-print-width": "------",
"TEST": "comma IS added here"
}
flow-sequence:
[
"object-does-not-fit-within-print-width", "------",
"TEST", "comma IS added here"
]
# Prettier 2.1
mapping:
{
"object-does-not-fit-within-print-width": "------",
"TEST": "comma IS added here",
}
flow-sequence:
[
"object-does-not-fit-within-print-width",
"------",
"TEST",
"comma IS added here",
]
# Prettier 2.2
flow-mapping:
{
"object-does-not-fit-within-print-width": "------",
"TEST": "comma IS added here"
}
flow-sequence:
[
"object-does-not-fit-within-print-width",
"------",
"TEST",
"comma IS added here"
]
Corregir comentarios dentro de flowMapping y flowSequence (#9669 por @fisker)
# Input
a:
[
a, b,
# comment
]
b:
# prettier-ignore
{
a: 1, b: 2,
# comment
}
# Prettier 2.1
a: [a, b]
# comment
b:
# prettier-ignore
{
a: 1, b: 2,
# comment
}
# comment
# Prettier 2.1 (second format)
a:
[a, b]
# comment
b:
# prettier-ignore
{
a: 1, b: 2,
# comment
}
# comment
# comment
# Prettier 2.2
a: [
a,
b,
# comment
]
b:
# prettier-ignore
{
a: 1, b: 2,
# comment
}
API
Dejar de inferir el parser json para archivos .jsonl (#9371 por @fisker)
// Prettier 2.1
$ prettier --check .
Checking formatting...
[error] bad.jsonl: SyntaxError: Unexpected token (2:1)
[error] 1 | '{"type": "t/f", "head": "England", "relation": "invaded", "tail": "United States"}'
[error] > 2 | '{"type": "t/f", "head": "England", "relation": "attacked", "tail": "Baltimore"}'
[error] | ^
[error] 3 |
All matched files use Prettier code style!
// Prettier 2.2
$ prettier --check .
Checking formatting...
All matched files use Prettier code style!
Vaciar contenidos de sufijo de línea al final del documento (#9703 por @dangmai)
Prettier no vaciaba los contenidos de sufijo de línea al final del documento si no había salto de línea final. Esta corrección fuerza el vaciado completo incluso sin saltos de línea finales.
CLI
Trasladar la compatibilidad con pre-commit a github.com/pre-commit/mirrors-prettier (#8937 por @FloChehab)
La compatibilidad con pre-commit se ha trasladado a https://github.com/pre-commit/mirrors-prettier. Por favor, actualice su archivo .pre-commit-config.yaml.
- - repo: https://github.com/prettier/prettier
+ - repo: https://github.com/pre-commit/mirrors-prettier
- rev: "2.2.0"
+ rev: "v2.2.0"
hooks:
- id: prettier
Corrección: error en directorios y archivos con nombres numéricos (#9298 por @fisker)
$ cat 1/index.js
hello('world')
// Prettier 2.1
$ prettier 1
[error] The "path" argument must be of type string. Received type number (1)
// Prettier 2.2
$ prettier 1
hello("world");
