本页

deno fmt,代码格式化

Deno 附带一个内置的代码格式化程序,它将自动格式化以下文件

文件类型 扩展名
JavaScript .js
TypeScript .ts
JSX .jsx
TSX .tsx
Markdown .md, .markdown
JSON .json
JSONC .jsonc

此外,deno fmt 可以格式化 Markdown 文件中的代码片段。代码片段必须用三个反引号括起来,并具有语言属性。

# format all supported files in the current directory and subdirectories
deno fmt
# format specific files
deno fmt myfile1.ts myfile2.ts
# format all supported files in specified directory and subdirectories
deno fmt src/
# check if all the supported files in the current directory and subdirectories are formatted
deno fmt --check
# format stdin and write to stdout
cat file.ts | deno fmt -

忽略代码 跳转到标题

通过在 TS/JS/JSONC 中的代码前面加上 // deno-fmt-ignore 注释来忽略格式化代码

// deno-fmt-ignore
export const identity = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1,
];

或者通过在文件顶部添加 // deno-fmt-ignore-file 注释来忽略整个文件。

在 Markdown 中,您可以使用 <!-- deno-fmt-ignore --> 注释,或者使用 <!-- deno-fmt-ignore-file --> 注释来忽略整个文件。要忽略 Markdown 的一部分,请用 <!-- deno-fmt-ignore-start --><!-- deno-fmt-ignore-end --> 注释将代码括起来。

配置 跳转到标题

ℹ️ 建议坚持使用默认选项。

从 Deno v1.14 开始,可以使用 配置文件 或以下 CLI 标志来自定义格式化程序

  • --use-tabs - 是否使用制表符。默认为 false(使用空格)。

  • --line-width - 打印机尝试保持在下的行宽。请注意,打印机在某些情况下可能会超过此宽度。默认为 80。

  • --indent-width - 缩进的字符数。默认为 2。

  • --no-semicolons - 除必要情况外,不使用分号。

  • --single-quote - 是否使用单引号。默认为 false(使用双引号)。

  • --prose-wrap={always,never,preserve} - 定义如何在 Markdown 文件中换行散文。默认为 "always"。

注意:在 Deno 版本 < 1.31 中,您必须在这些标志前加上 options-(例如 --options-use-tabs