Bird
Raised Fist0
Denoframework~15 mins

deno fmt for code formatting - Deep Dive

Choose your learning style10 modes available
Overview - deno fmt for code formatting
What is it?
deno fmt is a built-in tool in the Deno runtime that automatically formats your code to follow consistent style rules. It reads your source files and rewrites them with proper indentation, spacing, and line breaks. This helps keep your code clean and easy to read without manual effort. You can run it from the command line or integrate it into your development workflow.
Why it matters
Without a tool like deno fmt, developers would spend extra time manually fixing code style issues or face inconsistent formatting across a project. This inconsistency makes code harder to read, review, and maintain. deno fmt saves time and reduces errors by enforcing a uniform style automatically, improving collaboration and code quality.
Where it fits
Before using deno fmt, you should know basic Deno commands and how to write simple Deno scripts. After learning deno fmt, you can explore other Deno developer tools like deno lint for code quality and deno test for testing. It fits early in the Deno learning path as a foundational tool for clean code.
Mental Model
Core Idea
deno fmt is like a smart editor that rewrites your code to look neat and consistent every time you save or run it.
Think of it like...
Imagine you have a messy desk with papers scattered everywhere. deno fmt is like a helpful assistant who organizes all your papers neatly in folders and stacks, so everything looks tidy and easy to find.
Source Code (messy) ──▶ deno fmt ──▶ Source Code (clean & consistent)

┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│  Your Code    │──────▶│  deno fmt     │──────▶│ Formatted Code│
│ (inconsistent)│       │ (formatter)   │       │ (consistent)  │
└───────────────┘       └───────────────┘       └───────────────┘
Build-Up - 6 Steps
1
FoundationWhat is deno fmt and why use it
🤔
Concept: Introducing deno fmt as a code formatter built into Deno.
deno fmt is a command-line tool that formats your Deno code files automatically. It fixes indentation, spacing, and line breaks to follow a standard style. You run it by typing 'deno fmt' in your terminal inside your project folder. It supports TypeScript, JavaScript, JSON, and more.
Result
Your code files are rewritten with consistent formatting rules applied.
Understanding that deno fmt automates code styling saves you from manual formatting and keeps your codebase uniform.
2
FoundationRunning deno fmt on your project
🤔
Concept: How to use deno fmt command to format files.
Open your terminal in your Deno project folder. Run the command: deno fmt This will format all supported files in the current folder and subfolders. You can also specify files or folders: deno fmt ./src deno fmt file.ts The tool overwrites files with formatted versions.
Result
All specified files are formatted according to Deno's style rules.
Knowing how to run deno fmt manually is the first step to integrating it into your workflow.
3
IntermediateCustomizing deno fmt behavior
🤔Before reading on: do you think deno fmt allows full custom style rules or only limited options? Commit to your answer.
Concept: Exploring configuration options for deno fmt using a config file.
deno fmt supports a configuration file named 'deno.json' or 'deno.jsonc' where you can specify formatting options under the 'fmt' key. For example, you can set line width, indent width, and whether to use tabs or spaces: { "fmt": { "lineWidth": 80, "indentWidth": 2, "useTabs": false } } This config file should be in your project root. deno fmt reads it automatically.
Result
deno fmt formats code according to your specified style preferences.
Knowing that deno fmt can be customized helps you align formatting with your team's style without losing automation benefits.
4
IntermediateIntegrating deno fmt in development workflow
🤔Before reading on: do you think deno fmt is best run manually or can it be automated? Commit to your answer.
Concept: Using deno fmt automatically during development to keep code clean continuously.
You can integrate deno fmt into your workflow by: - Running it before commits using git hooks (e.g., Husky or simple scripts). - Adding it to your editor's save actions (many editors support running commands on save). - Including it in your CI/CD pipeline to ensure all code is formatted before merging. Example git hook script: "pre-commit": "deno fmt" This ensures no unformatted code is committed.
Result
Code is always formatted consistently without manual effort.
Automating deno fmt usage prevents style drift and reduces review overhead.
5
AdvancedHow deno fmt handles different file types
🤔Before reading on: do you think deno fmt formats only TypeScript or other files too? Commit to your answer.
Concept: Understanding the range of file types deno fmt supports and how it applies formatting rules.
deno fmt supports formatting for: - TypeScript (.ts, .tsx) - JavaScript (.js, .jsx) - JSON (.json) - Markdown (.md) - TOML (.toml) It uses the same formatting engine for all, applying rules appropriate to each syntax. This means you can keep all your project files neat with one tool.
Result
Multiple file types in your project are formatted consistently by deno fmt.
Knowing deno fmt's multi-file support simplifies toolchain and reduces context switching.
6
ExpertInternal formatting engine and performance
🤔Before reading on: do you think deno fmt parses code fully or just applies text rules? Commit to your answer.
Concept: How deno fmt parses and rewrites code using Deno's internal parser for accuracy and speed.
deno fmt uses Deno's built-in TypeScript compiler APIs to parse source code into an abstract syntax tree (AST). It then rewrites the code from this tree applying formatting rules. This approach ensures formatting respects language syntax and semantics, avoiding broken code. Because it uses native Deno APIs, deno fmt is fast and reliable. It also shares code with deno lint and other tools, ensuring consistency.
Result
Formatted code is syntactically correct and style-consistent with minimal performance cost.
Understanding that deno fmt works on parsed code explains why it never breaks syntax and why it is fast.
Under the Hood
deno fmt works by reading your source files and parsing them into a structured format called an abstract syntax tree (AST) using Deno's TypeScript compiler APIs. It then applies formatting rules to this tree and regenerates the source code text with consistent indentation, spacing, and line breaks. This process ensures the code remains syntactically correct while improving readability. The tool overwrites the original files with the formatted versions.
Why designed this way?
deno fmt was designed to integrate tightly with Deno's runtime and compiler to provide a seamless developer experience. Using the compiler's AST ensures formatting respects language syntax and avoids errors common in simple text-based formatters. The built-in nature removes the need for external dependencies, simplifying setup and improving performance. Alternatives like external formatters were rejected to keep Deno self-contained and consistent.
┌───────────────┐
│ Source Files  │
└──────┬────────┘
       │ Read
       ▼
┌───────────────┐
│   Parser      │
│ (AST Builder) │
└──────┬────────┘
       │ AST
       ▼
┌───────────────┐
│ Formatter     │
│ (Applies     │
│  style rules) │
└──────┬────────┘
       │ Formatted Code
       ▼
┌───────────────┐
│ Overwrite     │
│ Source Files  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does deno fmt change your code's behavior or just style? Commit to yes or no.
Common Belief:deno fmt might change how the code runs because it rewrites files.
Tap to reveal reality
Reality:deno fmt only changes whitespace, indentation, and formatting; it never alters code logic or behavior.
Why it matters:Believing deno fmt changes behavior can make developers hesitant to use it, missing out on cleaner code benefits.
Quick: Can you fully customize every formatting rule in deno fmt? Commit to yes or no.
Common Belief:You can customize every detail of code style with deno fmt.
Tap to reveal reality
Reality:deno fmt offers limited customization focused on common options like indent size and line width, but not full style control like some other formatters.
Why it matters:Expecting full customization may lead to frustration; understanding limits helps choose the right tool or accept defaults.
Quick: Does deno fmt require installing extra packages? Commit to yes or no.
Common Belief:You need to install a separate formatter package to use deno fmt.
Tap to reveal reality
Reality:deno fmt is built into the Deno runtime; no extra installation is needed.
Why it matters:Knowing this reduces setup time and confusion for beginners.
Quick: Does deno fmt format files outside your project folder by default? Commit to yes or no.
Common Belief:deno fmt formats all files on your computer by default.
Tap to reveal reality
Reality:deno fmt only formats files in the current directory and its subdirectories unless you specify otherwise.
Why it matters:Misunderstanding scope can cause accidental formatting of unintended files or confusion about what was formatted.
Expert Zone
1
deno fmt uses the same parser as the TypeScript compiler, so it respects language features and experimental syntax, avoiding formatting errors common in regex-based tools.
2
When multiple config files exist, deno fmt merges settings hierarchically, allowing per-folder overrides, which is useful for monorepos with different style needs.
3
deno fmt's performance scales well even on large codebases because it processes files asynchronously and caches parsing results internally.
When NOT to use
deno fmt is not suitable if you need highly customized formatting rules beyond its limited options. In such cases, consider using specialized formatters like Prettier with Deno integration. Also, if you work in mixed-language projects with unsupported file types, deno fmt alone won't cover all formatting needs.
Production Patterns
In production, teams often run deno fmt automatically in pre-commit git hooks to prevent unformatted code from entering the repository. CI pipelines include deno fmt checks to enforce style consistency. Editors are configured to run deno fmt on save, providing immediate feedback. Large projects use deno.json config files to standardize formatting across teams.
Connections
Prettier (code formatter)
Alternative tool with broader customization but external to Deno.
Understanding deno fmt's built-in nature helps appreciate tradeoffs compared to Prettier's flexibility and ecosystem.
Compiler Abstract Syntax Tree (AST)
deno fmt formats code by manipulating the AST generated by the compiler.
Knowing how ASTs represent code structure clarifies why deno fmt can format without breaking syntax.
Quality Control in Manufacturing
Both enforce consistent standards automatically to ensure uniform output quality.
Seeing deno fmt as a quality control step helps understand its role in maintaining codebase health.
Common Pitfalls
#1Running deno fmt without saving files first, expecting changes to appear immediately in editor.
Wrong approach:Run 'deno fmt' in terminal but keep editor unsaved; wonder why code looks unchanged.
Correct approach:Save all files in editor before running 'deno fmt' or configure editor to format on save.
Root cause:deno fmt formats files on disk; unsaved editor changes are not affected.
#2Trying to customize deno fmt with unsupported options expecting full control.
Wrong approach:Adding unsupported keys in deno.json like 'singleQuote': true expecting effect.
Correct approach:Use only supported options like 'lineWidth', 'indentWidth', and 'useTabs' in deno.json under 'fmt'.
Root cause:Misunderstanding deno fmt's limited configuration scope.
#3Running deno fmt on a folder with non-code files expecting them to be formatted.
Wrong approach:deno fmt ./assets Expecting images or binary files to be formatted.
Correct approach:Run deno fmt only on folders containing supported source files.
Root cause:Not knowing deno fmt ignores unsupported file types.
Key Takeaways
deno fmt is a built-in Deno tool that automatically formats your code to a consistent style, saving time and improving readability.
It works by parsing your code into a structured format and rewriting it with proper indentation and spacing, ensuring syntax correctness.
You can run deno fmt manually or automate it in your development workflow to keep code clean continuously.
deno fmt supports multiple file types but offers limited customization compared to some external formatters.
Understanding how deno fmt integrates with Deno's compiler and tooling helps you use it effectively and avoid common mistakes.

Practice

(1/5)
1. What is the main purpose of the deno fmt command?
easy
A. To install third-party modules
B. To run your Deno program
C. To automatically format your code for better readability and consistency
D. To check for security vulnerabilities in your code

Solution

  1. Step 1: Understand the role of deno fmt

    deno fmt is designed to format code automatically, making it easier to read and consistent across files.
  2. Step 2: Differentiate from other commands

    Running programs, installing modules, or security checks are done by other commands like deno run, deno install, or deno lint.
  3. Final Answer:

    To automatically format your code for better readability and consistency -> Option C
  4. Quick Check:

    deno fmt formats code [OK]
Hint: Remember: fmt means format code automatically [OK]
Common Mistakes:
  • Confusing fmt with run or install commands
  • Thinking fmt checks code errors instead of formatting
  • Assuming fmt modifies program logic
2. Which of the following is the correct way to run deno fmt on all supported files in your project?
easy
A. deno fmt
B. deno fmt install
C. deno fmt run
D. deno fmt --check

Solution

  1. Step 1: Identify the basic command to format files

    Running deno fmt without extra flags formats all supported files in the current directory and subdirectories.
  2. Step 2: Understand other options

    --check only checks formatting without changing files; run and install are unrelated commands.
  3. Final Answer:

    deno fmt -> Option A
  4. Quick Check:

    Basic command to format = deno fmt [OK]
Hint: Use just 'deno fmt' to format all files quickly [OK]
Common Mistakes:
  • Adding unnecessary flags like run or install
  • Using --check when wanting to format files
  • Confusing fmt with other Deno commands
3. Given this unformatted TypeScript code in example.ts:
function greet ( name:string ){console.log( "Hello, " +name );}
What will be the output in example.ts after running deno fmt?
medium
A. function greet ( name:string ){console.log( "Hello, " +name );}
B. function greet(name: string) { console.log("Hello, " + name); }
C. function greet(name:string){console.log("Hello,"+name);}
D. function greet(name: string) {console.log("Hello," + name);}

Solution

  1. Step 1: Understand what deno fmt does to code style

    deno fmt adds spaces after commas, spaces around operators, and proper indentation and line breaks for readability.
  2. Step 2: Compare options with expected formatting

    function greet(name: string) { console.log("Hello, " + name); } shows proper spacing after parameters, braces on new lines, and indentation inside the function, matching deno fmt style.
  3. Final Answer:

    function greet(name: string) { console.log("Hello, " + name); } -> Option B
  4. Quick Check:

    deno fmt adds spaces and indentation [OK]
Hint: Look for spaces after colons and proper indentation [OK]
Common Mistakes:
  • Ignoring spaces after colons and commas
  • Not indenting inside function blocks
  • Keeping all code on one line
4. You run deno fmt --check on your project and get an error saying some files are not formatted. What should you do to fix this?
medium
A. Run deno fmt without flags to format the files automatically
B. Ignore the error because it does not affect code execution
C. Delete the files that are not formatted
D. Run deno run to fix formatting issues

Solution

  1. Step 1: Understand what deno fmt --check does

    This command checks if files are formatted but does not change them.
  2. Step 2: Fix formatting issues

    To fix formatting, run deno fmt without flags to automatically format all files.
  3. Final Answer:

    Run deno fmt without flags to format the files automatically -> Option A
  4. Quick Check:

    Use deno fmt to fix formatting [OK]
Hint: Use deno fmt (no flags) to fix formatting errors [OK]
Common Mistakes:
  • Ignoring formatting errors thinking they don't matter
  • Trying to fix formatting by running code
  • Deleting files instead of formatting
5. You want to ensure your project code is always formatted before committing to Git. Which command can you add to your Git pre-commit hook to automatically format all files using Deno?
hard
A. deno run
B. deno install
C. deno lint
D. deno fmt

Solution

  1. Step 1: Identify the command that formats code automatically

    deno fmt formats all supported files, making it ideal for pre-commit hooks to keep code clean.
  2. Step 2: Understand other commands' purposes

    deno run executes scripts, deno lint checks code style but does not fix formatting, and deno install installs scripts.
  3. Final Answer:

    deno fmt -> Option D
  4. Quick Check:

    Pre-commit formatting uses deno fmt [OK]
Hint: Use deno fmt in pre-commit hooks to auto-format code [OK]
Common Mistakes:
  • Using deno run or deno lint instead of fmt
  • Thinking lint fixes formatting automatically
  • Not automating formatting before commits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard