【问题标题】:How to check typescript type before commit?如何在提交前检查打字稿类型?
【发布时间】:2020-11-18 14:21:39
【问题描述】:

我想在提交前检查打字稿类型,所以我使用tsc --noEmit $(changedFile)。但是,这个命令不能指定config文件。

我找到了--project选项,但是这个选项会检查整个项目,我只想检查changedFile,因为有些old files有类型错误但不需要处理。

那么我怎样才能在提交之前只检查changedFile 类型呢?

【问题讨论】:

    标签: git typescript


    【解决方案1】:

    你可以使用一个很棒的库lint-staged。该库会在每次提交之前对您的文件进行 lint。
    https://github.com/okonet/lint-staged

    安装

    npx mrm lint-staged
    

    用法 TypeScript

    // lint-staged.config.js
    module.exports = {
      '**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit'
    }
    

    【讨论】:

    • 我只想检查当前提交时更改的文件。
    【解决方案2】:

    您可能想要使用 pre-commit 挂钩 (https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks)。

    它,您可以使用git diff --staged --name-only 获取即将提交的文件,然后您可以运行您的tsc --noEmit $(changedFile)

    【讨论】:

    • tsc --noEmit $(changedFile) 无法指定打字稿配置文件。
    【解决方案3】:

    tsc 不提供使用项目设置处理指定文件的直接方法(如果您将文件传递给tsc,则为ignores the config file),但它确实允许您extend 配置文件和覆盖其包含的文件列表,例如:

    $ cat ./tsconfig-temp.json
    
    {
        "extends": "./tsconfig.json",
        "include": ["./temp.ts"]
    }
    

    包装脚本可用于使用指定的文件即时生成这样的配置文件,例如(使用jo 创建 JSON):

    $ cat tsc-files.sh
    
    #!/usr/bin/bash
    
    TEMP='./tsconfig-temp.json'
    trap 'rm "$TEMP"' EXIT
    
    jo extends=./tsconfig.json include=$(jo -a "$@") > $TEMP \
        && tsc --noEmit --project "$TEMP"
    

    用法

    $ tsc-files.sh ./temp.ts
    

    或者,您可以在 npm 上使用 tsc-files 包,它会为您执行此操作:

    用法

    $ tsc-files --noEmit ./temp.ts
    

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,这个包帮助我检查了 lint-staged 中的类型:

      "**/*.ts?(x)": [
        "tsc-files --noEmit"
      ]
      

      你可以用npm i tsc-files安装tsc-files

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 2019-06-27
        相关资源
        最近更新 更多