deno fmt 從 prettier 切換到 dprint,性能提升 10+ 倍
如果問 Deno 的發(fā)布帶來了什么,最重要的無疑是將高性能的 Rust 工具鏈帶到了前端。
提到 JavaScript 總給人一種感覺:慢。

Deno 使用 TypeScript 和 Rust 開發(fā),Deno 除了可以運行 JS(X) 和 TS(X) 代碼外,還提供了其它命令行參數(shù)。比如?deno fmt,?deno lint,?deno doc?等等。今天我們的話題就是?deno fmt:代碼格式化工具。
運行?deno fmt --help?的輸出:
deno-fmt
Auto-format JavaScript/TypeScript source code.
deno fmt
deno fmt myfile1.ts myfile2.ts
deno fmt --check
Format stdin and write to stdout:
cat file.ts | deno fmt -
Ignore formatting code by preceding it with an ignore comment:
// deno-fmt-ignore
Ignore formatting a file by adding an ignore comment at the top of the file:
// deno-fmt-ignore-file
USAGE:
deno fmt [OPTIONS] [files]...
OPTIONS:
--check
Check if the source files are formatted.
-h, --help
Prints help information
-L, --log-level
Set log level [possible values: debug, info]
-q, --quiet
Suppress diagnostic output
By default, subcommands print human-readable diagnostic messages to stderr.
If the flag is set, restrict these messages to errors.
ARGS:
... 在最初的版本中,Deno 格式化工具使用的是 prettier。prettier 是前端非常非常流行的代碼格式化工具,在 npm 上的月下載量是三四千萬。
不久前 Deno 的格式化工具切換到了 dprint。大概一年前(2019年6月)David Sherret 開始開發(fā) dprint,最初是作為一個 Node.js 項目。今年開始作者將 dprint 的代碼都遷移到了 Rust。
dprint cli 本身并不處理文件的格式化,對特定類型文件格式化的操作是由插件提供,目前官方提供了 4 個插件可以用來格式化 ts/js、json、rust、markdown。這些插件也是使用 Rust 編寫,并被編譯為 wasm 和 crate(crate 是 Rust 的包)。
dprint 的所有插件都是 wasm 格式,而 deno fmt 則直接使用了 crate,因此在性能方面 deno fmt 要優(yōu)于 dprint。
我在自己的電腦上測試了一個包含 590 個文件的 TypeScript React 項目:
Formatted 590 files.
dprint fmt 7.82s user 3.05s system 326% cpu 3.334 total
deno fmt 4.41s user 2.49s system 748% cpu 0.921 total
prettier 15.77s user 4.28s system 124% cpu 16.042 total可以看到 dprint 是 prettier 的 5 倍,deno fmt 是 prettier 的 17 倍。
目前 dprint 還在快速迭代,將來還會有更多的格式化插件開發(fā)出來,這樣就可以更快的格式化更多的文件類型,比如 vue、css、pug 等等。
我已經(jīng)打算在下一個 React 項目中使用 deno fmt 代替 prettier 了。
除了 deno fmt 之外,deno lint?也已經(jīng)發(fā)布了 0.1.19 版。基準測試數(shù)據(jù)顯示 deno_lint 的性能大概是 eslint 的 14 倍。
