APIs

前面对代码进行格式化,是命令行工具的形式,这些命令行工具所提供的命令实际上也是调用 Prettier 背后对应的各种 API。

在官网能够查看到这些 API:https://prettier.io/docs/en/api.html

prettier.format(source, options)

这个 API 是整个 Prettier 最核心的 API,该 API 负责的就是格式化操作。

下面是一个使用该 API 进行代码格式化的例子:

const prettier = require("prettier");
const fs = require("fs");
const path = require("path");
 
// Prettier 规则配置
const options = {
  singleQuote: false,
  printWidth: 50,
  semi: false,
  trailingComma: "es5",
  parser: "babel", // 指定对应的解析器
};
 
// 读取 src 目录
fs.readdir("src", (err, files) => {
  if (err) throw err;
 
  for (let i = 0; i < files.length; i++) {
    // 拼接路径
    const sourcePath = path.resolve("src", files[i]);
    // 读取源码文件
    const jsSource = fs.readFileSync(sourcePath, "utf8");
    // 使用 prettier.format 来进行格式化
    // 通过 API 的方式来格式化,一定要指定 parser
    prettier.format(jsSource, options).then((res) => {
      // 将格式化好的结果重新写入到原来的文件里面
      fs.writeFileSync(sourcePath, res, "utf-8");
    });
  }
 
  console.log("格式化完毕...");
});

注意在使用 API 进行格式化时,格式化规则里面需要添加 parser,指定对应的解析器,关于能够添加哪些 parser,可以参阅:https://prettier.io/docs/en/options.html#parser

prettier.check(source, [options])

该 API 主要负责核对对应的文件是否符合 Prettier 格式。

实现简易 CLI

一个工具的 CLI 背后其实就是调用的对应的 API,我们这里来实现一个简易的 CLI 工具。

首先新建一个名为 formattool 项目,使用 pnpm init 进行初始化。然后在项目中新建一个 index.js,代码如下:

#!/usr/bin/env node
 
// 获取命令行参数
const args = process.argv.slice(2);
console.log(args);

主要要注意第一行代码,通常称之为 shebang(sharp bang),该代码是类 Unix(Linux、MacOS)操作系统所支持的一种特性,用于告诉操作系统如何执行之后的脚本,#! 后面会跟上解释器的绝对路径。

接下来进行一个全局的链接:

终端定位到在 formattool 项目根目录下,使用 npm link 进行全局链接。回到要链接的项目(prettier-demo),使用 npm link。formattool 链接刚才放到全局下面的 formattool 包。

回到 formattool 下面的 index.js 文件中,补充如下代码:

#!/usr/bin/env node
 
const prettier = require("prettier");
const fs = require("fs");
const path = require("path");
 
// 获取命令行参数
const args = process.argv.slice(2);
 
// 要做格式化的操作
// pnpm formattool --write src/index.js
 
// 读取源码
const sourcePath = path.resolve("src", "index.js");
const jsSource = fs.readFileSync(sourcePath, "utf8");
 
// 读取配置文件
const options = JSON.parse(fs.readFileSync(path.resolve(".prettierrc")));
 
if (args.length === 0) {
    console.error("请提供一个参数!");
    process.exit(1);
}
 
const input = args[0];
 
if (input === "--write" || input === "-w") {
    // 使用 Prettier 的 API 对代码进行格式化操作
    prettier.format(jsSource, options).then(res => {
        // 将格式化后的 js 代码重新写回到原来的文件
        fs.writeFileSync(sourcePath, res, 'utf-8');
    })
    console.log("格式化操作已经完成...");
}

在上面的代码中,调用了 Prettier 的 format 方法来对 src/index.js 文件进行格式化,并且将格式化后的内容写回到原来的文件。

之后在 prettier-demo 项目中,需要在 package.json 中添加一条命令:

"scripts": {
    // ...
    "formattool": "formattool"
},

之后就可以在控制台通过 pnpm formatool --writesrc/index.js 文件进行格式化操作。

注意,上面所完成的代码是一个最基本的演示,实际的 CLI 还需要做更多的处理。目的是清楚 CLI 背后的原理就是获取用户在命令行所输入的参数,然后调用对应的 API。