Prettier 2.7: ¡Nueva opción CLI --cache y sintaxis de TypeScript 4.7!
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 una nueva opción CLI --cache. Al habilitar esta opción, se utilizarán ciertos atributos como claves de caché y se formatearán los archivos solo si han cambiado. Esto podría mejorar drásticamente el rendimiento de la CLI.
¡También hemos añadido soporte para formatear la sintaxis de TypeScript 4.7!
Si disfrutas usando Prettier y quieres apoyar nuestro trabajo, considera patrocinarnos directamente a través de nuestro OpenCollective o patrocinando los proyectos de los que dependemos, incluyendo typescript-eslint, remark y Babel.
Destacados
TypeScript
Soporte para TypeScript 4.7 (#12896, #12897, #12898, #12900, #12921, #12924, #12959 por @sosukesuzuki)
¡Soporte para las nuevas características de TypeScript 4.7!
Expresiones de Instanciación
interface Box<T> {
value: T;
}
function makeBox<T>(value: T) {
return { value };
}
const makeHammerBox = makeBox<Hammer>;
const makeWrenchBox = makeBox<Wrench>;
Anotaciones de Varianza Opcionales
interface Animal {
animalStuff: any;
}
interface Dog extends Animal {
dogStuff: any;
}
type Getter<out T> = () => T;
type Setter<in T> = (value: T) => void;
Restricciones extends para infer
type FirstString<T> = T extends [infer S extends string, ...unknown[]]
? S
: never;
CLI
Añadidas opciones CLI --cache y --cache-strategy (#12800 por @sosukesuzuki)
Se han añadido dos nuevas opciones CLI para un sistema de caché similar al de ESLint.
Consulta la documentación para más detalles.
--cache
Si esta opción está habilitada, se utilizan los siguientes valores como claves de caché y el archivo se formatea solo si alguno de ellos cambia.
-
Versión de Prettier
-
Opciones
-
Versión de Node.js
-
(si
--cache-strategyescontent) contenido del archivo -
(si
--cache-strategyesmetadata) metadatos del archivo, como marcas de tiempo
prettier --write --cache src
--cache-strategy
Estrategia que usará la caché para detectar archivos modificados. Puede ser metadata o content. Si no se especifica ninguna estrategia, se usará content.
prettier --write --cache --cache-strategy metadata src
Otros cambios
JavaScript
Conservar línea en blanco entre especificadores de exportación (#12746 por @sosukesuzuki)
// Input
export {
// a
foo1,
// b
bar1,
baz1,
} from "mod";
// Prettier 2.6
export {
// a
foo1,
// b
bar1,
baz1,
} from "mod";
// Prettier 2.7
export {
// a
foo1,
// b
bar1,
baz1,
} from "mod";
Reconocer más patrones de llamadas como "callee de llamada de prueba" (#12779 por @HosokawaR)
Admite llamadas de prueba como test.describe de Playwright.
// Input
test.step("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe.only("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe.parallel("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe.parallel.only("does something really long and complicated so I have to write a very long name for the testThis is a very", () => {});
test.describe.serial("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe.serial.only("does something really long and complicated so I have to write a very long name for the test", () => {});
// Prettier 2.6
test.step(
"does something really long and complicated so I have to write a very long name for the test",
() => {}
);
test.describe(
"does something really long and complicated so I have to write a very long name for the test",
() => {}
);
test.describe.only(
"does something really long and complicated so I have to write a very long name for the test",
() => {}
);
test.describe.parallel(
"does something really long and complicated so I have to write a very long name for the test",
() => {}
);
test.describe.parallel.only(
"does something really long and complicated so I have to write a very long name for the testThis is a very",
() => {}
);
test.describe.serial(
"does something really long and complicated so I have to write a very long name for the test",
() => {}
);
test.describe.serial.only(
"does something really long and complicated so I have to write a very long name for the test",
() => {}
);
// Prettier 2.7
test.step("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe
.only("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe
.parallel("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe.parallel
.only("does something really long and complicated so I have to write a very long name for the testThis is a very", () => {});
test.describe
.serial("does something really long and complicated so I have to write a very long name for the test", () => {});
test.describe.serial
.only("does something really long and complicated so I have to write a very long name for the test", () => {});
Corregir formato de comentarios en (#12860 por @HosokawaR)
Este cambio corrige el formato de comentarios en exports para alinearlo con el formato de comentarios en import.
Aunque este cambio no afecta el formato de comentarios en import, el registro de cambios incluye ejemplos de comentarios en import como referencia.
// Input
export {
foo,
bar as // comment
baz,
}
import {
foo,
bar as // comment
baz,
} from 'foo'
// Prettier 2.6
export {
foo,
bar as baz, // comment
};
import {
foo,
// comment
bar as baz,
} from "foo";
// Prettier 2.7
export {
foo,
// comment
bar as baz,
};
import {
foo,
// comment
bar as baz,
} from "foo";
TypeScript
Imprimir as en lugar de : para el parser babel-ts (#12706 por @HosokawaR)
// Input
[x as any] = x;
// Prettier 2.6
[x: any] = x;
// Prettier 2.7
[x as any] = x;
Corregir formato para Enums de TypeScript con miembros computados (#12930 por @HosokawaR)
// Input
enum A {
[i++],
}
// Prettier 2.6
enum A {
i++,
}
// Prettier 2.7
enum A {
[i++],
}
Dejar de analizar código inválido (#12982 por @fisker)
// Input
const object = ({ methodName() });
// Prettier 2.6
const object = { methodName(); };
// Prettier 2.7
SyntaxError: Unexpected token. (1:29)
> 1 | const object = ({ methodName() });
| ^^
HTML
Admitir formato de Speculation Rules API en HTML (#12882 por @sosukesuzuki)
Consulte https://web.dev/speculative-prerendering/ para más información sobre Speculation Rules API.
<!-- Input -->
<script type="speculationrules">
{
"prerender": [
{"source": "list", "urls": ["https://a.test/foo"]}
]
}
</script>
<!-- Prettier 2.6 -->
<script type="speculationrules">
{
"prerender": [
{"source": "list", "urls": ["https://a.test/foo"]}
]
}
</script>
<!-- Prettier 2.7 -->
<script type="speculationrules">
{
"prerender": [{ "source": "list", "urls": ["https://a.test/foo"] }]
}
</script>
Vue
Permitir formato para expresiones de plantilla Vue escritas en TypeScript (#12584 por @sosukesuzuki)
<!-- input -->
<script setup lang="ts">
let x: string | number = 1
</script>
<template>
{{ (x as number).toFixed(2) }}
</template>
<!-- Prettier 2.6 -->
<script setup lang="ts">
let x: string | number = 1
</script>
<template>
{{ (x as number).toFixed(2) }}
</template>
<!-- Prettier 2.7 -->
<script setup lang="ts">
let x: string | number = 1;
</script>
<template>
{{ (x as number).toFixed(2) }}
</template>
Inferir parser Stylus para bloques de estilo en Vue SFC (#12707 por @lsdsjy)
Los bloques <style lang="stylus"> en Vue SFC pueden procesarse con el plugin adecuado si está disponible.
Evitar imprimir atributos por línea en bloques Vue SFC (#12895 por @sosukesuzuki)
<!-- Input (singleAttributePerLine: true) -->
<script lang="ts" setup>
</script>
<!-- Prettier 2.6 -->
<script
lang="ts"
setup
>
</script>
<!-- Prettier 2.7 -->
<script lang="ts" setup>
</script>
Angular
Corregir formato de propiedades shorthand (#12993 por @sosukesuzuki, @fisker)
<!-- Input -->
<ng-container *ngTemplateOutlet="someTmpl; context: { app }"></ng-container>
<!-- Prettier 2.6 -->
<ng-container
*ngTemplateOutlet="someTmpl; context: { app: this.app }"
></ng-container>
<!-- Prettier 2.7 -->
<ng-container *ngTemplateOutlet="someTmpl; context: { app }"></ng-container>
GraphQL
Admitir impresión de nodos SchemaExtension (#12519 por @trevor-scheer)
# Input
extend schema { subscription: Subscription }
extend schema @directive
# Prettier 2.6
N/A - throws error
# Prettier 2.7
extend schema {
subscription: Subscription
}
extend schema @directive
Corregir formato de descripciones vacías y de una sola línea (#12608 por @chimurai, @fisker)
# Input
""" Customer """
type Person {
name: String
}
""""""
type Person {
name: String
}
# Prettier 2.6.2
"""
Customer
"""
type Person {
name: String
}
"""
"""
type Person {
name: String
}
# Prettier 2.6.2 (second format)
"""
Customer
"""
type Person {
name: String
}
"""
"""
type Person {
name: String
}
# Prettier 2.7
"""
Customer
"""
type Person {
name: String
}
"""
"""
type Person {
name: String
}
CLI
Mostrar el número de archivos que necesitan cambios (#12561 por @Harry-Hopkinson)
# Prettier 2.6
$ prettier src --check
Checking formatting...
[warn] src/fileA.js
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
# Prettier 2.7
$ prettier src --check
Checking formatting...
[warn] src/fileA.js
[warn] src/fileB.js
[warn] Code style issues found in 2 files. Forgot to run Prettier?
$ prettier src --check
Checking formatting...
[warn] src/fileA.js
[warn] Code style issues found in the above file. Forgot to run Prettier?
Inferir analizador para archivos .importmap (#12603 por @fisker)
Formatear archivos .importmap como archivos JSON.
Simplificar prueba de rendimiento (#12682, #12698 por @fisker)
Cuando se pasan los flags --debug-benchmark o --debug-repeat:
-
La CLI omite imprimir código en pantalla o escribir archivos
-
Establece automáticamente el nivel de logs en
debug
