JavaScript をフォーマットする方法
一貫したインデント、空白、セミコロンで JavaScript コードを整形します。
问题
JavaScript が圧縮されていたりスタイルが不統一だったりして、読みにくくデバッグしづらい。
前提条件
- JavaScript 構文の理解
- コードフォーマッタへの習熟
ステップ
-
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. 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. 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
期待される結果
元の意味を保ちつつ、一貫したスタイルに整えた読みやすい JavaScript。
よくあるエラー
- 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.