跳到主要内容
uencoder

如何Format JavaScript

美化 JavaScript code with consistent indentation, spacing, and semicolons.

问题

你的 JavaScript 是 minified 或 inconsistently styled, making 它困难到 读取和 调试.

前置条件

  • Understanding 的 JavaScript syntax
  • 熟悉代码 formatters

步骤

  1. 1. Parse the JavaScript

    The formatter parses the code into an AST to understand its structure. This ensures formatting is based on syntax, not text patterns. Invalid syntax will cause an error.

    输入
    const x=1;function f(){return x+2}
    输出
    parsed AST
  2. 2. Apply style rules

    Add indentation based on block nesting. Insert spaces around operators and after commas. Add or enforce semicolons based on your style. Break long lines and align chained calls for readability.

    输入
    const x=1;function f(){return x+2}
    输出
    const x = 1;\nfunction f() {\n  return x + 2;\n}
  3. 3. Handle modern syntax

    Ensure the formatter supports modern JavaScript features: arrow functions, destructuring, template literals, optional chaining, and async/await. ES modules and TypeScript syntax should also be supported.

    输入
    const f=async(a,b)=>a?.b??c
    输出
    formatted modern JS

预期结果

Readable JavaScript 具有 consistent 风格该 preserves 原始 semantics.

常见错误

Formatted code has different behavior
Automatic semicolon insertion can change behavior in rare cases (e.g., lines starting with () or []). Use a formatter that handles ASI correctly.
Formatter does not support TypeScript
Use a formatter with TypeScript support, such as Prettier, to handle type annotations.

排障指引

  • If the formatter fails, the input has a syntax error. Fix it first.
  • Use Prettier or eslint --fix for industry-standard formatting.

安全限制

  • Formatting does not execute code. However, never eval() formatted code from untrusted sources.

相关工具

参考链接