JavaScript Formatter

0 characters

Browser-based JavaScript/TypeScript/JSX/TSX/CSS/HTML/JSON code formatter supporting Prettier-style fine-grained configuration, Terser minification and obfuscation, built-in CodeMirror editor with real-time preview, shortcut operations, file upload/download.

Related

Use Cases

  • Beautify and format minified third-party JS code pasted during frontend development for easier reading and debugging
  • Standardize JavaScript/TypeScript code formatting before team code reviews, eliminating style differences in indentation, quotes, semicolons to focus on logic review
  • One-click format messy legacy JS code when taking over existing projects to quickly understand code structure and logic hierarchy
  • Use Terser to minify and obfuscate JavaScript code before production deployment to reduce file size and improve page load speed
  • Keep code clean with real-time formatting when writing JS/JSX demos online for easy sharing with colleagues or the community
  • Preview formatting results instantly by adjusting options when learning Prettier configuration effects, understanding tabWidth, trailingComma and other parameter behaviors
  • Automatically fix indentation and newline issues when processing code snippets copied from Stack Overflow, GitHub and other platforms
  • Automatically format indentation and newlines when writing JSON configuration files to avoid parsing failures caused by comma or bracket errors
  • Format JS+CSS+HTML code together within the same project during CSS/HTML page development to maintain consistent style
  • Quickly organize JS algorithm code before interviews and exams to improve code presentation

How to Use

  1. Open the JavaScript formatter tool page, paste code directly into the left editor area, or click the upload button to select local files (supports .js/.ts/.jsx/.tsx/.css/.html/.json formats)
  2. Select the appropriate language type: The tool usually auto-detects, but if detection is inaccurate you can manually select JavaScript/TypeScript/JSX/TSX/CSS/HTML/JSON from the language dropdown
  3. Configure formatting options: Choose quick style presets (default/modern/classic), or manually adjust Prettier options (indent width, tabs/spaces, line width, semicolons, quotes, trailing commas, arrow parentheses)
  4. If you need to minify code, switch to minification mode, configure Terser minification options (enable compress, mangle variable names, compress top-level variables), CSS optimization level, HTML minification options
  5. The tool processes code in real-time, the right editor area instantly shows formatted or minified results, bottom status bar shows real-time character count, byte count, compression ratio statistics
  6. Use keyboard shortcuts to improve efficiency: Ctrl+Shift+B triggers formatting, Ctrl+Shift+M toggles minification mode, Ctrl+Shift+O opens files, Ctrl+Shift+D downloads results, Ctrl+Shift+K clears editor
  7. When satisfied, click the copy button to copy results to clipboard, or click the download button to save as local file; you can also click the share button to generate a URL link with code and configuration to share with others

Features

  • Multi-language support: Formats 7 commonly used frontend languages including JavaScript, TypeScript, JSX, TSX, CSS, HTML, JSON in one place for all frontend code processing needs
  • Prettier-style fine-grained configuration: Supports complete options including tabWidth indent width (2/4/8 spaces), useTabs tabs vs spaces, printWidth line width, semi semicolons, singleQuote single vs double quotes, trailingComma trailing commas, arrowParens arrow function parentheses
  • Code minification: Integrated Terser minification engine supporting production-grade options including compress code compression, mangle variable name obfuscation, toplevel top-level variable compression
  • CSS optimization: Provides CSS optimization level configuration supporting CSS minification, comment removal, whitespace removal and other specialized processing
  • HTML minification options: Supports HTML minify configuration with whitespace collapsing, comment removal, attribute quote removal and more
  • Real-time processing: Instant formatting preview as you type code, no button clicks needed to see formatting results
  • CodeMirror editor: Built-in professional CodeMirror editor providing syntax highlighting, line numbers, bracket matching, code folding and other professional editing experiences
  • File upload/download: Supports direct upload of local .js/.ts/.jsx/.tsx/.css/.html/.json files, one-click download of processed files after formatting
  • Shareable links: Save code and configuration via URL hash, generate shareable links to send to colleagues to reproduce the exact formatting scenario
  • History: Automatically saves formatting history to localStorage, allowing you to revisit previous code versions and configurations at any time
  • Keyboard shortcuts: Supports Ctrl+Shift+B format, Ctrl+Shift+M minify, Ctrl+Shift+O open file, Ctrl+Shift+D download, Ctrl+Shift+K clear and other quick operations
  • Quick presets: Provides 3 quick configuration presets: default, modern, classic for one-click switching between common styles
  • Character statistics: Real-time display of character count, byte count, and compression ratio comparison between original and processed code
  • Sample code: Built-in sample code for various languages, click to load and quickly experience features

FAQ

Will JavaScript code logic change after formatting?

No. Formatting only adjusts code whitespace, indentation, newlines, bracket positions, quote styles and other "formatting" related content, it's based on AST (Abstract Syntax Tree) transformation; code AST structure is completely identical before and after formatting, execution logic is 100% the same. As long as the code itself has correct syntax and can be parsed normally, formatting won't change any execution behavior and can be used safely. But while minification (mangle) doesn't change logic either, you need to pay attention to special scenarios like eval and global variable exports to avoid improper configuration.

What if formatter results differ from my local VS Code/Prettier formatting?

This tool's formatting logic tries to stay consistent with official Prettier behavior. If results differ, please check configuration items: whether these core options tabWidth, useTabs, semi, singleQuote, trailingComma, arrowParens are exactly the same on both sides. Also note Prettier version differences—Prettier 2/3 default configurations have subtle differences (v3 defaults to trailingComma: all, v2 defaults to es5; v2 onward arrowParens defaults to always). If your local project has .prettierrc configuration file, adjust options on the web page to match and formatting results will be the same.

Can minified code be restored? Can mangled variable names be recovered?

Formatted code is completely reversible—because only formatting changed, all identifiers and logic are fully preserved; formatting again will restore it. But for minified code: only whitespace/comment removal parts can be reformatted to restore layout, but mangle (variable name obfuscation) is irreversible—original meaningful variable names like userName become a, this process is one-way and cannot automatically restore original names. If you need to debug minified code in production, you should configure Source Map file generation to map back to source positions via Source Map. So always keep original unminified source code before minification!

Which browsers are supported? Can I use it on mobile?

This tool supports all modern browsers: latest Chrome, Firefox, Safari, Edge all work normally. IE browser not supported (nobody uses IE for development now either). Responsive layout adapts to mobile screens, but code editing on small screens has mediocre experience; desktop browser usage is recommended for higher efficiency on large screens. All formatting and minification calculations run locally in the browser, no need to upload code to servers, code never leaves your browser, safe and reliable.

Why can't some code be formatted, showing parse errors?

Formatters first need to parse code into AST to work; if code has syntax errors (bracket mismatch, unclosed strings, misspelled keywords, extra commas etc.), parser can't understand code structure and throws errors. Please check code itself for syntax errors first: check console for error messages, editor for red squiggles indicating error locations; after fixing syntax errors formatting will work normally. Also confirm correct language mode is selected; JSX/TSX code shouldn't be selected as plain JS.

Will my code be uploaded to servers? Is code safe?

No. All formatting, minification, syntax highlighting run entirely locally in your browser via JavaScript; code is never sent to any servers, completely processed on your device. You can test offline: disconnect network and tool still works normally. Share link feature encodes code and configuration into URL hash, clicking share only generates a URL, code isn't uploaded—but if you send the link to others they can see your code when opening it, so don't share sensitive code via links.

Can I format Vue Single File Components (.vue files)? What about Svelte?

Currently this tool's multi-language support includes JS/TS/JSX/TSX/CSS/HTML/JSON; Vue <template>/<script>/<style> Single File Components (SFC) and Svelte components aren't supported for direct overall formatting currently, but you can copy out script parts (JS/TS), style parts (CSS), template parts (HTML) separately and select corresponding languages for individual formatting. Vue/Svelte SFC formatting support will be considered for future additions.

How to set unified team formatting standards?

Three-layer coordination recommended for team unified standards: ① Place .editorconfig in project root to unify basic editor settings (indentation, newlines, encoding); ② Use Prettier with .prettierrc configuration file in project, everyone and CI format with this configuration, this tool can also select corresponding options to match configuration; ③ Use ESLint + eslint-config-prettier to disable ESLint style rules, only check code quality. Configure editor auto-format on save (VS Code install Prettier extension, set editor.formatOnSave: true), add lint step in CI to check format ensuring committed code conforms to standards.

What are benefits of trailing commas (trailingComma)? Should I enable them?

Trailing commas are strongly recommended (at least es5 level, all level recommended). Benefits of trailing commas: ① Cleaner Git diffs: when adding the last element no need to modify previous line to add comma, only new line diff, no previous line diff pollution from adding comma; ② More convenient when rearranging element order, no need to handle trailing comma issues; ③ Modern browsers and Node.js fully support trailing commas; old IE doesn't support but no need to consider IE now. Only downside is one extra comma, completely worth it compared to convenience. Prettier v3 defaults to all.

Should I enable mangle during minification? What's difference between compress and mangle?

Production minification recommends enabling both compress and mangle; these are independent minification options: compress is code optimization (constant folding, dead code removal, expression simplification etc.), only modifying code structure when simplifiable without changing variable names; mangle is local variable name shortening changing long variable names to single characters, one of the largest volume reduction sources. As long as your code isn't a library where external code directly calls variable names, or doesn't use eval to dynamically access variable names, mangle is safe and can significantly reduce volume. If open source library needs to preserve API names, configure mangle.reserved to preserve exported names.

Why does certain characters get automatically escaped when formatting JSON?

JSON specification has strict syntax requirements: strings must use double quotes, no trailing commas, special characters must be escaped (newline→\n, quote→\", backslash→\\, Tab→\t etc.). If your JSON strings have unescaped special characters, formatting automatically escapes them according to JSON specification which is correct behavior. Note: JSON isn't JavaScript; you can't write comments in JSON, can't use single quotes, can't have undefined—these all cause JSON parsing failures.

How to make arrow function parameters always have parentheses? Or no parentheses?

Adjust arrowParens option: always always adds parentheses ((x) => x), this is Prettier v2+ default, benefit is adding/removing parameters doesn't require adding/removing parentheses, cleaner diffs; avoid omits parentheses for single parameters (x => x), more concise code. Choose according to team style; neither style is right or wrong, just be consistent. Note: parameter type annotations, default parameters, destructured parameters always have parentheses regardless of configuration.

Can formatting automatically fix ESLint-reported style issues?

This tool is Prettier-style formatting, can only fix style issues handled by Prettier (indentation, quotes, semicolons, trailing commas, line width, spaces etc.). ESLint-reported code quality issues (like unused variables, missing return, === issues) are logic problems that formatters can't automatically fix and require manual modification. If your ESLint is configured with eslint-config-prettier, then after Prettier formatting ESLint won't report style-related errors anymore, remaining quality issues can be fixed manually.

What's the maximum supported code file size? Will large file formatting lag?

Because formatting runs locally in browser, supported file size depends on your device performance; generally JS files from tens of KB to several MB can be processed normally, single-file JS from ordinary projects is completely sufficient. If it's an especially large bundled JS file (tens of MB) there may be lag or even insufficient memory; such ultra-large files are recommended to be processed locally using Node.js+Prettier/Terser command line. Individual source files in daily development are usually within processing range.

Why does Ctrl+Shift+B in Chrome open bookmarks manager?

This is Chrome browser default shortcut conflict: Ctrl+Shift+B is Chrome's show/hide bookmarks bar shortcut; browser shortcut priority is higher than web page JS shortcuts so it gets intercepted by Chrome. Solutions: ① Click formatting button to operate; ② If you're Mac user Cmd+Shift+B won't conflict with Chrome; ③ You can modify browser shortcuts in Chrome settings; ④ You can focus inside editor first; editor focus can capture shortcut in some cases. If other browsers also have shortcut conflicts you can always operate via buttons.

Troubleshooting

"Syntax parse error" during formatting, cannot format

Code itself has syntax errors: bracket mismatch, unclosed strings, missing keywords, extra commas etc.; syntax errors cause AST parsing failure making formatting impossible, please fix syntax errors first Incorrect language mode selection: for example JSX/TSX code selected as JavaScript, generic syntax misjudged as JSX tags or vice versa, please manually select the correct language type Contains experimental syntax: code uses too-new JavaScript syntax proposals not yet standardized (like decorators, Pipeline operator), parser doesn't support File has BOM header: UTF-8 BOM (EF BB BF) three bytes at beginning; some parsers may not handle this, try saving as UTF-8 without BOM Mixed in other language code: for example template languages embedded in HTML (EJS, Handlebars, Vue template directives) aren't pure JS/HTML, parser can't recognize Unclosed block comments in code: /* without corresponding */, unclosed comments cause subsequent code to be treated entirely as comments Regex ambiguity: certain places that look like division/operators are actually regex literals, parser misjudges; you can add a semicolon before regex to eliminate ambiguity

Error during minification (Minify), cannot minify

Code syntax errors: like formatting, minification is also based on AST; code must be syntactically correct to minify, fix syntax errors first Using ES Module import/export without correctly marking module type, or minification configuration doesn't match module type Issues when mangling property names: if property name mangle is enabled (default off), dynamic property access obj['key'] causes properties not found; don't enable property mangle casually eval() or with statements in code: Terser may have mangle errors when encountering eval/with because eval can dynamically access scope variable names; avoid using eval in production code Reserved name configuration errors: if mangle.reserved is configured but misspelled or missing required reserved names (like jQuery, $ and other global libraries), runtime errors may occur toplevel minification configuration issues: if your code runs in global scope rather than bundled in IIFE/module, enabling compress.toplevel: true may break global variable references Target browser version configured too old: Terser may use syntax not supported by target browsers during minification; you can configure ecma version to specify output JS syntax version

Chinese/Chinese comments display garbled after formatting

File encoding not UTF-8: uploaded local file is in GBK/GB2312 and other Chinese encodings, tool defaults to UTF-8 parsing causing garbled text; use editor to resave file as UTF-8 encoding before uploading Browser page encoding accidentally modified: although modern browsers default to UTF-8, some old browsers or special settings may have incorrect encoding; check browser menu page encoding set to UTF-8 File has UTF-8 BOM header: while BOM usually doesn't cause garbled text, some parsers handle BOM abnormally; use editor to remove BOM and save as UTF-8 without BOM Encoding conversion issues during copy-paste: when copying code from certain old software (like old Notepad, Word), special characters (like Chinese quotes, full-width spaces) may be incorrectly converted; try copying from modern editors like VS Code Font issues: some monospace fonts have poor Chinese support causing display anomalies; this isn't an encoding issue just display font issue, switch to a Chinese-supporting monospace font Special Unicode characters: code contains emoji, zero-width spaces, control characters and other special invisible characters that may cause display anomalies or formatting errors; you can enable editor invisible character display to check gzip compression or proxy issues: if garbled text appears after deployment, check whether server correctly sets Content-Type: application/javascript; charset=utf-8 response header

JSX/TSX code formatting fails or parse errors

Language mode selected as JavaScript instead of JSX/TSX: regular JS parser doesn't recognize <tag> syntax, treats JSX tags as comparison operators causing errors; please manually select JSX or TSX language TSX generic syntax ambiguity: <T> generic parameter in TSX may be misjudged as JSX tag like const f = <T>(x: T) => x; you can add a comma after <T> as <T,> to eliminate ambiguity (this is common TSX practice) Unclosed JSX tags: JSX requires all tags to be properly closed, self-closing tags must have />, unlike HTML where <img> must be written as <img/> JS expression bracket issues in JSX: JS expressions in {} must be properly closed; {obj.prop} without closing } causes subsequent parsing chaos Fragment shorthand issues: <></> empty tags require React 16+ support and must be properly closed; if using <Fragment> need correct import JSX attribute value quote issues: JSX attribute values that are strings must use quotes (double quotes), expressions use {}, don't mix TSX file extension is .ts instead of .tsx: TypeScript parser only enables JSX parsing for .tsx extension; writing JSX with .ts extension causes errors, use correct extension

Indentation incorrect after formatting, doesn't match expectations

Incorrect tabWidth configuration: check whether indent width is configured as 2 or 4, teams commonly use 2 spaces; if expecting 4 spaces manually adjust tabWidth option Incorrect useTabs configuration: if team uses Tab indent but you configured spaces or vice versa, check useTabs option is correct Code itself has syntax errors: syntax errors cause abnormal AST structure resulting in messy indentation after formatting; first fix syntax errors indicated by red squiggles Mixed Tab and spaces: original code has some Tab indentation some spaces; formatting will unify to configured style but severe original code mess may require multiple formatting passes printWidth set too small: if line width is set too small (like 40), code wraps frequently making indentation look messy; setting to 80 or 100 is more appropriate bracketSameLine/arrowParens and other layout options not matching expectations: brace position, arrow function parentheses and other styles are determined by configuration not indentation issues; adjust corresponding options EditorConfig and local editor configuration conflict: if local editor uses .editorconfig auto-indentation that differs from web page configured options, formatting results on both sides will be inconsistent; unify configuration

Keyboard shortcuts not working, pressing has no response

Focus not on editor: shortcuts only work when editor has focus; if focus is on buttons, input boxes or other page areas shortcuts won't trigger, click editor area first to focus Browser shortcut conflicts: some shortcuts (like Ctrl+Shift+B in Chrome opens bookmarks bar, Ctrl+Shift+O in Firefox opens history) are taken by browser; you can click button operations, or try Cmd instead of Ctrl (Mac) Input method issues: some shortcuts may be intercepted in Chinese input method state; switch to English input method then try shortcuts Other extensions/plugins occupied: browser-installed shortcut extensions, Tampermonkey scripts, proxy plugins may occupy shortcuts; try opening page in incognito mode System shortcut conflicts: OS or other running software (like screenshot software, input methods, IDE) global shortcuts occupy corresponding key combinations; you can modify other software shortcuts or use this tool's button operations Mac/Windows keyboard differences: note Mac uses Cmd (⌘) key, Windows/Linux use Ctrl key, don't mix; Mac Option corresponds to Windows Alt Browser security restrictions: certain shortcuts involving file access may be limited by browser security policies and cannot be fully simulated via JS; when necessary directly click corresponding button operations

Glossary

Prettier
Currently the most popular frontend code formatter, adopting an Opinionated design philosophy, supporting multiple languages including JS/TS/CSS/HTML/Markdown, enforcing unified code style and ending team style debates.
Terser
Modern JavaScript minification tool, an ES6+-compatible fork of UglifyJS, supporting ES6+ syntax minification and obfuscation, the default minifier for modern build tools like Webpack, Rollup, Vite.
UglifyJS
Classic JavaScript minification tool, predecessor to Terser, but only supports ES5 and earlier syntax without ES6+ new features; new projects generally use Terser instead now.
AST (Abstract Syntax Tree)
Abstract Syntax Tree, a tree representation of source code syntactic structure where each node represents a syntactic structure in code. Babel, Prettier, Terser, ESLint and other tools are all implemented based on AST.
ESLint
The most popular code checking tool (Linter) in the JavaScript/TypeScript ecosystem for discovering code quality issues and unifying code style, can be used together with Prettier.
EditorConfig
Cross-editor code style unification configuration file defining basic settings like indent style, indent size, newlines, encoding etc., making different editors behave consistently when opening the same project.
CodeMirror
Browser-side code editor component providing professional editing features like syntax highlighting, line numbers, bracket matching, code folding, multiple cursors, one of the mainstream choices for web-based code editors.
minify
The process of minimizing code volume without changing code logic by removing whitespace, comments, shortening variable names, code optimization etc., used in production environments to improve load speed.
mangle
The step during minification that shortens variable names, function names, parameters to single characters, significantly reducing code volume while making code harder to read, also called variable name obfuscation.
beautify
Code formatting, re-indenting, wrapping, adding spaces to minified or messy code to improve readability, the opposite of minify.
trailing comma
Commas after the last element in objects, arrays, function parameters, facilitating cleaner Git diffs when adding elements, supported in ES5+ environments.
arrow parens
Whether single-parameter arrow function parameters need parentheses, e.g., x => x (no parens) vs (x) => x (with parens).
printWidth
Character count per line after which automatic wrapping occurs during formatting; Prettier defaults to 80 characters, teams can adjust to 100 or 120 based on monitor size.
semicolons
Whether to add semicolons at JavaScript statement ends; JS has ASI automatic semicolon insertion mechanism but semicolons are still recommended in most scenarios to avoid accidents.
single quote
Using single quotes vs double quotes for strings; functionally equivalent in JS, just style preference; JSON specification mandates double quotes.
double quote
Using double quotes to wrap strings, the default style for many languages and the string format required by JSON specification.
tab width
Number of spaces per indentation level; frontend community commonly uses 2 spaces, backend languages commonly use 4 spaces.
BOM (Byte Order Mark)
Byte Order Mark, three bytes EF BB BF that may appear at the beginning of UTF-8 encoded files to mark encoding; may cause JS parsing errors in some scenarios.
UTF-8
Unicode Transformation Format 8-bit, currently the standard file encoding for Web and frontend projects, supporting all Unicode characters, the recommended default encoding.
source map
File mapping minified/transpiled code back to original source positions for production debugging, allowing source line number location when minified code reports errors.

Prettier Core Options Reference

JavaScript Code Before/After Minification Comparison

Keyboard Shortcuts Quick Reference