Saltar al contenido principal

Navegador

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 →

Ejecuta Prettier en el navegador utilizando su versión standalone. Esta versión no depende de Node.js. Solo formatea el código y no incluye soporte para archivos de configuración, archivos ignore, uso CLI ni carga automática de plugins.

La versión standalone está disponible como:

  • Módulos ES: standalone.mjs, a partir de la versión 3.0 (En la versión 2, esm/standalone.mjs.)

  • UMD: standalone.js, a partir de la versión 1.13

El campo browser en el package.json de Prettier apunta a standalone.js. Por eso puedes simplemente import o require el módulo prettier para acceder a su API, manteniendo tu código compatible tanto con Node como con el navegador siempre que uses webpack u otro empaquetador que soporte el campo browser. Esto es especialmente conveniente para plugins.

prettier.format(code, options)

Opciones requeridas:

  • parser (o filepath): Debes especificar una de estas opciones para que Prettier sepa qué parser usar.

  • plugins: Unlike the format function from the Node.js-based API, this function doesn’t load plugins automatically. The plugins option is required because all the parsers included in the Prettier package come as plugins (for reasons of file size). These plugins are files in https://unpkg.com/browse/prettier@3.8.3/plugins. Note that estree plugin should be loaded when printing JavaScript, TypeScript, Flow, or JSON.

    You need to load the ones that you’re going to use and pass them to prettier.format using the plugins option.

Consulta los ejemplos a continuación.

Uso

Global

<script src="https://unpkg.com/prettier@3.8.3/standalone.js"></script>
<script src="https://unpkg.com/prettier@3.8.3/plugins/graphql.js"></script>
<script>
(async () => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: prettierPlugins,
});
})();
</script>

Nota que el campo unpkg en el package.json de Prettier apunta a standalone.js, por eso https://unpkg.com/prettier también puede usarse en lugar de https://unpkg.com/prettier/standalone.js.

Módulos ES

<script type="module">
import * as prettier from "https://unpkg.com/prettier@3.8.3/standalone.mjs";
import * as prettierPluginGraphql from "https://unpkg.com/prettier@3.8.3/plugins/graphql.mjs";

const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: [prettierPluginGraphql],
});
</script>

AMD

define([
"https://unpkg.com/prettier@3.8.3/standalone.js",
"https://unpkg.com/prettier@3.8.3/plugins/graphql.js",
], async (prettier, ...plugins) => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
});

CommonJS

const prettier = require("prettier/standalone");
const plugins = [require("prettier/plugins/graphql")];

(async () => {
const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins,
});
})();

Esta sintaxis no funciona necesariamente en el navegador, pero puede usarse al empaquetar el código con browserify, Rollup, webpack u otro empaquetador.

Worker

import * as prettier from "https://unpkg.com/prettier@3.8.3/standalone.mjs";
import * as prettierPluginGraphql from "https://unpkg.com/prettier@3.8.31/plugins/graphql.mjs";

const formatted = await prettier.format("type Query { hello: String }", {
parser: "graphql",
plugins: [prettierPluginGraphql],
});

Plugins de parser para código embebido

Si deseas formatear código embebido, también necesitas cargar los plugins relacionados. Por ejemplo:

<script type="module">
import * as prettier from "https://unpkg.com/prettier@3.8.3/standalone.mjs";
import * as prettierPluginBabel from "https://unpkg.com/prettier@3.8.3/plugins/babel.mjs";
import * as prettierPluginEstree from "https://unpkg.com/prettier@3.8.3/plugins/estree.mjs";

console.log(
await prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
parser: "babel",
plugins: [prettierPluginBabel, prettierPluginEstree],
}),
);
// Output: const html = /* HTML */ `<DIV> </DIV>`;
</script>

El código HTML embebido en JavaScript permanece sin formatear porque el parser html no se ha cargado. Uso correcto:

<script type="module">
import * as prettier from "https://unpkg.com/prettier@3.8.3/standalone.mjs";
import * as prettierPluginBabel from "https://unpkg.com/prettier@3.8.3/plugins/babel.mjs";
import * as prettierPluginEstree from "https://unpkg.com/prettier@3.8.3/plugins/estree.mjs";
import * as prettierPluginHtml from "https://unpkg.com/prettier@3.8.3/plugins/html.mjs";

console.log(
await prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
parser: "babel",
plugins: [prettierPluginBabel, prettierPluginEstree, prettierPluginHtml],
}),
);
// Output: const html = /* HTML */ `<div></div>`;
</script>