Saltar al contenido principal

Prettier 1.17: Más opciones para comillas y soporte para configuraciones compartidas

· 6 min de lectura
Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Esta versión introduce la tan solicitada flexibilidad para comillas en propiedades de objetos, permite compartir configuraciones de Prettier mediante paquetes, añade un parser LWC, agrega soporte para nueva sintaxis GraphQL y corrige múltiples errores de formato.

Destacados

JavaScript

Añade opción para modificar cuándo Prettier aplica comillas en propiedades de objetos (#5934 por @azz)

--quote-props <as-needed|preserve|consistent>

as-needed (predeterminado) - Solo añade comillas en propiedades de objetos cuando son requeridas. Comportamiento actual. preserve - Respeta la entrada original. Útil para usuarios del Closure Compiler de Google en modo avanzado, que trata propiedades entrecomilladas de forma diferente. consistent - Si al menos una propiedad en un objeto requiere comillas, aplica comillas a todas las propiedades - similar a la opción consistent-as-needed de ESLint.

// Input
const headers = {
accept: "application/json",
"content-type": "application/json",
"origin": "prettier.io"
};

// Output (Prettier 1.16 or --quote-props=as-needed)
const headers = {
accept: "application/json",
"content-type": "application/json",
origin: "prettier.io"
};

// Output (--quote-props=consistent)
const headers = {
"accept": "application/json",
"content-type": "application/json",
"origin": "prettier.io"
};

// Output (--quote-props=preserve)
const headers = {
accept: "application/json",
"content-type": "application/json",
"origin": "prettier.io"
};

Configuración

Soporte para configuraciones compartidas (#5963 por @azz)

Compartir una configuración de Prettier es sencillo: publica un módulo que exporte un objeto de configuración, como @company/prettier-config, y refiérelo en tu package.json:

{
"name": "my-cool-library",
"version": "9000.0.1",
"prettier": "@company/prettier-config"
}

Si prefieres no usar package.json, puedes emplear cualquier extensión soportada para exportar una cadena, por ejemplo .prettierrc.json:

"@company/prettier-config"

@azz ha creado un paquete de configuración de ejemplo. Puedes ver el código en GitHub o instalarlo vía npm.

nota

Este método no ofrece forma de extender la configuración para sobrescribir propiedades. Si necesitas hacerlo, importa el archivo en .prettierrc.js y exporta las modificaciones, ej:

module.exports = {
...require("@company/prettier-config"),
semi: false,
};

General

JavaScript

Respetar saltos de línea entre parámetros (#5836 por @evilebottnawi)

// Input
function foo(
one,

two,
three,
four,


five,
six,
seven,
eight,
nine,
ten,

eleven

) {}

// Output (Prettier 1.16)
function foo(
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven
) {}

// Output (Prettier 1.17)
function foo(
one,

two,
three,
four,

five,
six,
seven,
eight,
nine,
ten,

eleven
) {}

Corregir comentarios en importaciones dinámicas multilínea (#6025 por @noahsug)

// Input
import(
/* Hello */
'something'
/* Hello */
)
import(
'myreallylongdynamicallyloadedmodulenamemyreallylongdynamicallyloadedmodulename'
)

// Output (Prettier stable)
import(/* Hello */
"something");
/* Hello */
import('myreallylongdynamicallyloadedmodulenamemyreallylongdynamicallyloadedmodulename');

// Output (Prettier master)
import(
/* Hello */
'something'
/* Hello */
)
import(
'myreallylongdynamicallyloadedmodulenamemyreallylongdynamicallyloadedmodulename'
);

Añadir paréntesis para funciones y clases construidas inmediatamente (#5996 por @bakkot)

// Input
new class {};
new function() {}

// Output (Prettier stable)
new class {}();
new function() {}();

// Output (Prettier master)
new (class {})();
new (function() {})();

Corregir lógica de paréntesis en expresiones de encadenamiento opcional y casts de tipo Closure (#5843 por @yangsu)

La lógica introducida en #4542 colocaba paréntesis en posiciones incorrectas y generaba código inválido para expresiones de encadenamiento opcional (con más de 2 nodos) o casts de tipo Closure que terminaban en llamadas a funciones.

// Input
(a?.b[c]).c();
let value = /** @type {string} */ (this.members[0]).functionCall();

// Output (Prettier stable)
a(?.b[c]).c();
let value = /** @type {string} */ this(.members[0]).functionCall();

// Output (Prettier master)
(a?.b[c]).c();
let value = /** @type {string} */ (this.members[0]).functionCall();

Markdown

No alinear contenido de tablas cuando excede el ancho de impresión y --prose-wrap never está activado (#5701 por @chenshuai2144)

Las tablas alineadas son menos legibles que las compactas cuando son extensas y el ajuste de palabras está desactivado en el editor, por lo que ahora se imprimen como tablas compactas en estos casos.

<!-- Input -->
| Property | Description | Type | Default |
| -------- | ----------- | ---- | ------- |
| bordered | Toggles rendering of the border around the list | boolean | false |
| itemLayout | The layout of list, default is `horizontal`, If a vertical list is desired, set the itemLayout property to `vertical` | string | - |

<!-- Output (Prettier stable, --prose-wrap never) -->
| Property | Description | Type | Default |
| ---------- | --------------------------------------------------------------------------------------------------------------------- | ------- | ------- |
| bordered | Toggles rendering of the border around the list | boolean | false |
| itemLayout | The layout of list, default is `horizontal`, If a vertical list is desired, set the itemLayout property to `vertical` | string | - |

<!-- Output (Prettier master, --prose-wrap never) -->
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| bordered | Toggles rendering of the border around the list | boolean | false |
| itemLayout | The layout of list, default is `horizontal`, If a vertical list is desired, set the itemLayout property to `vertical` | string | - |

TypeScript

Soporte para operador readonly (#6027 por @ikatyang)

// Input
declare const array: readonly number[];

// Output (Prettier stable)
// SyntaxError: ',' expected.

// Output (Prettier master)
declare const array: readonly number[];

HTML

Añadir soporte para Lightning Web Components (#5800 por @ntotten)

Soporta el formato de plantilla Lightning Web Components (LWC) para atributos HTML mediante un nuevo parser llamado lwc.

// Input
<my-element data-for={value}></my-element>

// Output (Prettier stable)
<my-element data-for="{value}"></my-element>

// Output (Prettier master)
<my-element data-for={value}></my-element>

Angular: No añadir paréntesis innecesarios en pipes (#5929 por @voithos)

En algunos casos, se añadían paréntesis innecesarios a ciertas tuberías (pipes) dentro de atributos, pero ya no se añaden cuando no afectan el resultado de la expresión.

// Input
<div *ngIf="isRendered | async"></div>

// Output (Prettier stable)
<div *ngIf="(isRendered | async)"></div>

// Output (Prettier master)
<div *ngIf="isRendered | async"></div>

GraphQL

Soporte para directivas de variables (#6020 por @adek05)

Prettier ahora soporta el formateo de directivas de variables.

// Input
query Q($variable: Int @directive) {node}

// Output (Prettier stable)
query Q($variable: Int) {
node
}

// Output (Prettier master)
query Q($variable: Int @directive) {
node
}

Soporte para variables de fragmentos en GraphQL (#6016 por @adek05)

Prettier ahora soporta el formateo de variables de fragmentos.

// Input
fragment F($var: Int) on Type { node }

// Output (Prettier stable)
// Fails to parse

// Output (Prettier master)
fragment F($var: Int) on Type {
node
}

CLI

Descubrimiento automático de plugins con ámbito (#5945 por @Kocal)

Prettier ahora soporta la carga automática de plugins con ámbito denominados @scope-name/prettier-plugin-*.