如何生成tsconfig.json文件?

447

我该如何通过命令行生成 tsconfig.json 文件?我尝试过使用 tsc init 命令,但似乎不起作用。

17个回答

706

从 TypeScript 1.6 版本开始支持此功能。

正确的命令是--init而非init

$ tsc --init

尝试在您的控制台中运行以下内容以检查版本:

$ tsc -v
如果版本低于1.6,您需要进行更新:
$ npm install -g typescript

记住,你需要安装node.js才能使用npm。


3
如果像我一样,这个方法对你没有起作用 - 请尝试在这个答案中提供的解决方案:https://dev59.com/aWUp5IYBdhLWcg3wZG8c#32532656。干杯! - prestonsmith
19
我能够在不进行全局安装的情况下使其工作:npm i typescriptnpx tsc --init - Andreas Warberg
2
对于本地安装,node_modules/.bin/tsc --init - burntsugar
17
这个答案是否过时?npx tsc --init 返回 "Unknown compiler option 'init'."。 该答案目前没有过时。这是一条命令行错误消息,表明您使用的 TypeScript 版本不支持 --init 这个选项。您可以尝试升级 TypeScript 版本或使用其他相关命令来生成 TypeScript 配置文件。 - Andy Ray
1
@nathanfranke,你绝不能使用sudo安装库,并且--force与此安装问题无关。这可能意味着你正在将其安装到系统安装的node中,而不是使用nvm安装到用户(你)安装的node中。 - Andy Ray
显示剩余2条评论

86

对于那些通过以下方式在本地安装了 TypeScript(可能是作为依赖项或开发依赖项)的用户:

$ npm install typescript --save-dev

...并且将tsc脚本添加到package.json中的人:

"scripts": {
   ...
   "tsc": "tsc"
},

您可以通过npm调用tsc --init

$ npm run tsc -- --init 

1
为什么在tsc和--init之间需要两个破折号? - lorless
13
@lorless 这是一个分隔符,因此 -- 之后的所有内容被视为脚本自身的参数,不会被 npm 解析。 - Bojan Komazec

77

如果您不想全局安装TypeScript(这对我来说很有意义,因此您不需要经常更新它),您可以使用npx:

npx -p typescript tsc --init
关键点是使用 -p 标志,告知 npx 命令 tsc 二进制文件属于 typescript 包。

13
为什么不直接使用 npx tsc --init 呢?如果 Typescript 安装为本地开发依赖项,则 tsc 存在于 node_modules/.bin/tsc 中。 - tenni

56

您需要安装typescript库,然后才能使用。

npx tsc --init 

如果响应是error TS5023:未知编译器选项“init”。 这意味着库未安装

yarn add --dev typescript

或者适用于npm

npm i --save-dev typescript

然后再次运行npx命令。

我建议不要全局安装依赖项,因为这样可以更轻松地为每个项目管理版本。对于同事来说,只需要一个命令即可看到并安装运行项目所需的内容。


我遇到了这个错误:"This is not the tsc command you are looking for"。不过使用 npx typescript --init 命令可以解决。 - Boris K

29

以下方法对我有效:

tsc --init

13
安装TypeScript:
npm install typescript

在 package.json 中添加 tsc 脚本:

"scripts": {
  "tsc": "tsc"
 },

运行这个:

npm run tsc -- --init

10
npm install -g typescript 
tsc --init 

有时在全局更新typescript之后,您可能需要将其添加到当前项目中。

npm install typecsript ts-node nodemon - 如果您需要它。


简单的笔误。应该是 tsc --init 而不是 int :-) - Mugilan Ragupathi

9

我正在使用这个。

yarn add -D typescript
yarn tsc --init

这对我解决了问题。

8

按照以下步骤设置ts项目:

  • 安装typescript yarn global add typescript
  • 创建一个package.json: 运行 yarn init 或者使用默认设置 yarn init -yp
  • 创建一个tsconfig.json: 运行 tsc --init
  • (*可选) 添加 tslint.json

项目结构如下:

│  package.json
│  tsconfig.json
│  tslint.json
│  yarn.lock
│
├─dist
│      index.js
│
└─src
       index.ts


3
生成tsconfig文件的正常方式是创建一个名为tsconfig.json的文件,然后打开{},在这个{}里按下

ctrl + spacebar(Windows)

cmd + spacebar(mac)

然后选择compilationOptions,再选择所需的选项。


要使用VSCode终端或任何位于要创建的目录上的CMD自动生成(tsconfig.json):

tsc --init


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接