关于typescript:如何生成tsconfig.json文件?

How can I generate a tsconfig.json file?

如何通过命令行生成tsconfig.json
我尝试了命令tsc init,但这不起作用。


自TypeScript 1.6发行以来受支持。

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

1
$ tsc --init

尝试在控制台中运行以下命令以检查版本:

1
$ tsc -v

如果版本早于1.6,则需要更新:

1
$ npm install -g typescript

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


对于那些通过以下方式将TypeScript作为本地软件包(可能还作为dev依赖项)安装的用户:

1
$ npm install typescript --save-dev

...以及将tsc脚本添加到package.json的人:

1
2
3
4
"scripts": {
   ...
  "tsc":"tsc"
},

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

1
$ npm run tsc -- --init

这对我有用:

1
tsc --init

如果您不想在全球范围内安装Typescript(这对我来说很有意义,因此您不需要不断地对其进行更新),则可以使用npx:

1
npx -p typescript tsc --init

关键点是使用-p标志通知npx tsc二进制文件属于typescript包


按以下步骤设置ts项目:

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

项目结构如下:

1
2
3
4
5
6
7
8
9
10
│  package.json
│  tsconfig.json
│  tslint.json
│  yarn.lock

├─dist
│      index.js

└─src
       index.ts

安装TypeScript:

1
npm install typescript

将tsc脚本添加到package.json:

1
2
3
"scripts": {
 "tsc":"tsc"
 },

运行此:

1
npx tsc --init

$ npm run tsc -- --init
这适用于以下package.json

1
2
3
4
5
6
7
 "devDependencies": {
   "@types/jasmine":"^3.6.2",
   "@types/node":"^14.14.19",
   "jasmine":"^3.6.3",
   "protractor":"^7.0.0",
   "typescript":"^4.1.3"
  },

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

1
npx tsc --init

如果响应为error TS5023: Unknown compiler option 'init'.,则表示未安装该库

1
yarn add --dev typescript

并再次运行npx命令


我正在使用它,

1
yarn tsc --init

这为我修复了它


我建议先使用以下命令来卸载typescript:

1
npm uninstall -g typescript

然后使用Chocolatey包运行:

1
choco install typescript

在PowerShell中。