Aller au contenu
uencoder

Comment en Formater JavaScript

Embellir JavaScript code with consistent indentation, spacing, and semicolons.

问题

Your JavaScript est minified ou inconsistently styled, making it hard en lire et déboguer.

Prérequis

  • Understanding of JavaScript syntax
  • Familiarity with code formatters

Étapes

  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.

    entrée
    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.

    entrée
    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.

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

Résultat attendu

Readable JavaScript avec consistent style ce preserves le original semantics.

Erreurs courantes

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.

Dépannage指引

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

Limites de sécurité

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

Outils associés

参考链接