vscode 自定义 task, 以运行 Jest 测试当前文件为例

192 阅读1分钟

自定义 task, 以运行 jest 测试当前文件为例

{
    "version": "2.0.0",
    "tasks": [
        {
          "label": "Run tests",
          "type": "shell",
          "windows": {
            "command": "npx jest ${fileBasename}"
          },
          "group": "test",
          "presentation": {
            "reveal": "always",
            "panel": "dedicated"
          },
        }
      ]
}

说明:

  • label: 该 task 的唯一标识
  • type: 默认有 shellprocess 两种,后者是创建一个子进程
  • command: 要运行的具体命令。
  • args: 提供的参数。
  • group: 组别,默认有 test, build 两组。
  • presentation: 有关输出的一些配置
    • panel: 设置为 new 时将打开一个新的终端运行
    • reveal: 设置为 silent 将会在看不见的终端上运行,如果没有该终端,则新建一个终端。
  • options: 提供了下面三个配置项
    • cwd:工作目录
    • env:环境变量
    • shell:可以用来指定 shell。
  • runOptions: 指示 tasks 的如何运行以及何时运行。
  • 更多配置可参考 tasks.json schema

注意⚠️:

如果只使用 command 执行命令,那么很简单,该命令就是终端上运行的命令。但如果同时使用 commandargs,那么就要确保 command 中不要添加参数,参数应该统一添加在 args 中。下面举一个错误的使用示例:

"command": "npx jest"
"args": [
    "${fileBasename}"
]

错误原因在于 command 中提供了参数,此时 npx jest 会被认为是单独的一个执行程序,并且由于有空格,所以会用引号将其包括起来,所以最后执行的命令是 'npx jest' ${fileBasename} 此时系统就会提供找不到对应命令。

文章来自:learn-vscode - github