xDocxDoc
AI
前端
后端
iOS
Android
Flutter
AI
前端
后端
iOS
Android
Flutter
  • 关于

    • Prettier
    • 构建并强制执行
    • Prettier vs. Linters
    • 选项设计原理
    • 设计理念
  • 使用

    • 安装指南
    • 忽略代码
    • precommit
    • 插件
    • CLI
    • API
    • Browser
    • CI
  • 配置 Prettier

    • options
    • Configuration File
    • 共享配置
  • Editors

    • 编辑器集成
    • WebStorm 设置
    • Vim 配置指南
    • 监视文件变更
  • Misc

    • 技术实现细节
    • 生态
    • 企业解决方案

Browser

通过 独立版本 在浏览器中运行 Prettier。此版本不依赖 Node.js,仅提供代码格式化功能,不支持配置文件、忽略文件、CLI 或自动加载插件。

独立版本提供两种格式:

  • ES 模块:standalone.mjs(v3.0+),v2 版本路径为 esm/standalone.mjs
  • UMD 格式:standalone.js(v1.13+)

Prettier 的 package.json 中 https://github.com/defunctzombie/package-browser-field-spec指向 standalone.js,因此可通过 import 或 require 访问 API,兼容 Node 和浏览器环境(需配合 webpack 等支持 browser 字段的打包器)。此特性对plugins.md尤其便利。

prettier.format(code, options)

必填选项:

  • 解析器标识:必须指定以下任一选项

    • options.md#parser:明确指定解析器
    • options.md#file-path:通过文件扩展名推断解析器
  • 插件加载:与 api.md#prettierformatsource-options 不同,此函数不会自动加载插件。由于所有解析器都以插件形式提供(为控制文件体积),必须通过 plugins 选项显式加载。插件文件位于: https://unpkg.com/browse/prettier@%PRETTIER_VERSION%/plugins

    ⚠️ 重要提示:格式化 JavaScript/TypeScript/Flow/JSON 时必须加载 estree 插件

使用示例

全局引入

<!-- 加载核心库和插件 -->
<script src="https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.js"></script>
<script src="https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/graphql.js"></script>

<script>
  (async () => {
    const formatted = await prettier.format(
      "type Query { hello: String }", 
      {
        parser: "graphql",
        plugins: prettierPlugins, // 使用全局注册的插件
      }
    );
    console.log("GraphQL 格式化结果:", formatted);
  })();
</script>

路径说明:
Prettier 的 package.json 中 unpkg 字段指向 standalone.js,因此 https://unpkg.com/prettier 等价于完整路径

ES 模块

<script type="module">
  // 动态导入核心库和插件
  import * as prettier from "https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.mjs";
  import * as graphqlPlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/graphql.mjs";

  const formatted = await prettier.format(
    "type Query{hello:String}", 
    {
      parser: "graphql",
      plugins: [graphqlPlugin], // 插件数组
    }
  );
  document.body.textContent = formatted;
</script>

AMD 规范

// 异步加载依赖
define([
  "https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.js",
  "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/graphql.js",
], async (prettier, ...plugins) => {
  const formatted = await prettier.format(
    "type Query { hello: String }", 
    {
      parser: "graphql",
      plugins, // 展开插件数组
    }
  );
  return formatted;
});

CommonJS 规范

// 适用于打包工具(webpack/Rollup等)
const prettier = require("prettier/standalone");
const graphqlPlugin = require("prettier/plugins/graphql");

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

Web Worker 支持

// 现代浏览器支持的ES模块化Worker
import * as prettier from "https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.mjs";
import * as graphqlPlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/graphql.mjs";

self.onmessage = async (event) => {
  const formatted = await prettier.format(event.data.code, {
    parser: "graphql",
    plugins: [graphqlPlugin],
  });
  self.postMessage(formatted);
};
// 兼容旧浏览器的Worker
importScripts(
  "https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.js",
  "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/graphql.js",
);

self.onmessage = async (event) => {
  const formatted = await prettier.format(event.data.code, {
    parser: "graphql",
    plugins: prettierPlugins, // 全局插件对象
  });
  self.postMessage(formatted);
};

嵌入式代码的解析器插件

格式化options.md#embedded-language-formatting时需加载对应插件:

<script type="module">
  import * as prettier from "https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.mjs";
  import * as babelPlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/babel.mjs";
  import * as estreePlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/estree.mjs";

  // 未加载HTML插件时的格式化结果
  const result1 = await prettier.format(
    'const html=/* HTML */ `<DIV> </DIV>`', 
    {
      parser: "babel",
      plugins: [babelPlugin, estreePlugin],
    }
  );
  console.log(result1); 
  // 输出: const html = /* HTML */ `<DIV> </DIV>`;
</script>

HTML 代码未格式化是因为缺少对应插件:

<script type="module">
  import * as prettier from "https://unpkg.com/prettier@%PRETTIER_VERSION%/standalone.mjs";
  import * as babelPlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/babel.mjs";
  import * as estreePlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/estree.mjs";
  import * as htmlPlugin from "https://unpkg.com/prettier@%PRETTIER_VERSION%/plugins/html.mjs";

  // 正确加载所有插件
  const result2 = await prettier.format(
    'const html=/* HTML */ `<DIV> </DIV>`', 
    {
      parser: "babel",
      plugins: [babelPlugin, estreePlugin, htmlPlugin],
    }
  );
  console.log(result2); 
  // 输出: const html = /* HTML */ `<div></div>`;
</script>

浏览器环境使用总结

场景解决方案注意事项
基础引入通过 unpkg 加载 standalone 文件注意版本号替换(%PRETTIER_VERSION%)
插件机制显式加载所需语言插件JS/TS 必须包含 estree 插件
嵌入式代码加载宿主语言+嵌入语言双插件如 JSX 需加载 babel+html
模块系统支持 ES Modules/AMD/CommonJS根据运行环境选择合适方案
Web Worker支持传统和模块化 Worker避免阻塞主线程
生产部署建议下载插件本地托管避免依赖 unpkg 的运行时加载

核心差异(vs Node.js 环境):

  1. 无文件系统访问:无法读取本地配置/忽略文件
  2. 手动插件管理:必须显式加载所有解析器插件
  3. 功能精简:仅保留核心格式化能力
  4. 体积敏感:建议按需加载插件控制资源大小

性能提示:对于复杂项目,建议通过构建工具(如 webpack)将所需插件打包为单一资源,避免浏览器并发加载多个脚本。

最后更新: 2025/8/26 10:07
Prev
API
Next
CI