【问题标题】:tsc does not recognize '--init' optiontsc 无法识别“--init”选项
【发布时间】:2020-09-16 11:28:10
【问题描述】:

由于某种原因npx tsc --init 打印出以下错误:

$ npx tsc --init
npx: installed 1 in 1.467s
error TS5023: Unknown compiler option 'init'.

我已经用 Yarn 2 安装了typescript 包:

$ yarn add -D typescript
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed in 0.31s
➤ YN0000: ┌ Fetch step
➤ YN0013: │ typescript@npm:3.9.3 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ typescript@patch:typescript@npm%3A3.9.3#builtin<compat/typescript>::version=3.9.3&hash=8cac75 can't be found in the cache and will be fetched from the disk
➤ YN0000: └ Completed in 1.46s
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done in 1.95s

有人可以向我解释为什么tsc 无法识别--init 以及我做错了什么吗?


更新

正如 Daniel 发现的那样,问题在于 npx 无法找到或识别使用 Yarn 2 安装的 typescript 软件包。解决方案是改用yarnyarn tsc --init

【问题讨论】:

    标签: node.js typescript yarnpkg tsc


    【解决方案1】:

    npx tsc --init 的输出来看,您似乎没有在运行命令的目录中安装typescript 包。 npx 尝试通过安装运行命令所需的任何软件包来提供帮助。

    尽管它试图提供帮助,但最终没有安装预期在 2020 年安装的软件包。如果您运行 $ npx tsc -v,您很可能会得到以下输出:

    $ npx tsc -v
    npx: installed 1 in 1.098s
    message TS6029: Version 1.5.3
    

    但是,如果您安装了 typescript 软件包,您会得到这个:

    $ npx tsc -v
    Version 3.9.3
    

    如您所见,npm 安装的版本不同。那是因为npx 最终安装了tsc而不是typescripttsc 包还提供了一个tsc 命令。 npx 选择它而不是 typescript,因为虽然两个包都提供了 tsc 命令,但它也被称为 tscnpx 认为它更合适。

    更新:

    Yarn 2 引入了Plug'n'Play 功能。依赖项的安装方式与 Yarn 1 和 npm 过去的安装方式非常不同。

    Yarn 1 和npm 将包的代码放在每个项目的node_modules 目录中。 npx 去那里寻找命令。

    另一方面,Yarn 2 将包代码安装在共享位置,并在您的项目中放置一个执行映射的 .pnp.js 文件。如果您为一个项目安装了一个包,那么如果您在另一个项目中使用它,则无需再次下载它。

    但是,任何依赖于 node_modules 的工具都将被破坏。这就是为什么npx 无法在您的项目中找到typescriptnpx 不知道Plug'n'Play

    您可以在此处阅读有关此功能的更多信息:https://yarnpkg.com/features/pnp

    【讨论】:

    • 虽然这似乎是真的,但yarn 不应该将typescript 包安装在npx 可以找到它的目录中吗?根据documentation npx 还检查$PATH。由于yarn 被设计为npm 的替代品并且它也在$PATH 中,它不应该立即工作吗?顺便说一句,我在docs 中安装了类似推荐的 yarn 2
    • 纱线 2?这是拼图中缺失的部分。我已经更新了答案。
    • 是的.. 我忘了在我最初的帖子中提到这一点.. -.- 顺便说一句,谢谢!
    • 我不是 100% 确定我是否理解了解释,但混合 yarn 和 npm 对我的情况有帮助,所以 yarn add -D typescript &amp;&amp; yarn tsc --init ...
    【解决方案2】:

    对于其他人来到这里没有使用yarnnpx,在我的情况下解决它:

    npm install -g typescript --force

    编辑

    1. 我知道它没有回答确切的问题,但它确实处理了相同的错误。
    2. 我的npm 解决方案的可能解释:之前有问题,可能安装了tsc 而不是typescript,或者之前的typescript 安装本身存在问题。 npm install 将再次安装 typescript,--force 标志用于忽略现有的本地文件并覆盖它们。

    【讨论】:

    • 了解为什么这是一个很好的解决方案以及 force 选项在这里的作用会有所帮助。
    猜你喜欢
    • 2019-08-30
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2014-08-21
    • 2020-07-02
    • 2018-02-06
    • 2020-05-17
    相关资源
    最近更新 更多