tsc 无法识别“--init”选项

tsc does not recognize '--init' option

出于某种原因 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 包。解决方案是使用 yarn 代替:yarn tsc --init

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 无法在您的项目中找到 typescript 的原因。 npx 不知道 Plug'n'Play

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

对于其他来这里的人,他们不使用 yarn 也不使用 npx,在我的情况下解决了它:

npm install -g typescript --force

编辑

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