生成一个 tsconfig.json 文件
How to generate a tsconfig.json file
要生成tsconfig.json
文件:
- 在项目的根目录中打开终端。
- 全局安装打字稿:
npm install typescript@latest -g
. - 通过运行生成一个
tsconfig
文件tsc --init
:
在项目的根目录(package.json
文件所在的位置)中打开终端并运行以下命令:
# 👇️ install typescript globally npm install typescript@latest -g # 👇️ generate tsconfig.json file tsc --init
第一个命令typescript
全局安装最新版本的包,第二个命令生成一个tsconfig.json
文件。
typescript
失败,您可能必须运行前缀为sudo
.# 👇️ If you got permissions error, run with sudo sudo npm install typescript@latest -g tsc --init
如果能运行tsc --version
命令得到typescript包的版本号,则说明安装成功。
tsc --version
或者,您可以在本地安装 typescript 并tsconfig.json
从本地安装生成文件。
# 👇️ install typescript locally npm install --save-dev typescript # 👇️ generate tsconfig.json file tsc --init
该tsc --init
命令会生成一个
tsconfig.json
文件,表示该目录是 TypeScript 项目的根目录。
tsconfig.json
文件在对象中设置了一些选项,并对每个选项的作用进行了注释。 compilerOptions
如果您需要更改默认配置,您可以通过访问
tsconfig.json 参考页面获取有关每个选项的更多信息。
例如,如果您正在tsconfig.json
为 Node.js 项目生成一个文件,您的文件最终可能看起来类似于以下内容:
{ "compilerOptions": { "target": "es6", "module": "commonjs", "moduleResolution": "node", "rootDir": "src", "outDir": "build", "lib": ["ES2022"], "strict": true, "esModuleInterop": true, "allowJs": true, "checkJs": false, "resolveJsonModule": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, }, "include": ["src/**/*"], "exclude": ["node_modules"] }
此配置假定您src
在项目的根目录中有一个目录。
您可以在目录中创建一个index.ts
文件src
并运行
tsc src/index.ts
命令将其转换为 JavaScript。
上面的示例使用
include选项指定要包含在代码库中的模式。
tsconfig.json
文件的目录进行解析。exclude数组包含解析数组时应跳过的文件名或模式include
。
exclude
选项会更改该include
选项找到的内容,有效地从编译中过滤掉一些文件夹或文件。如果您没有exclude
在文件中显式添加数组tsconfig.json
,它默认为node_modules
,bower_components
和jspm_packages
。
target选项设置发出的 JavaScript 文件的语言版本。
所有现代浏览器(和 Node.js)都支持所有 ES6 特性。例如,当您的target
选项设置为早于{‘ ‘} 的内容时es6
(例如es5
),TypeScript 必须将您的类转换为函数。
您可以在tsconfig.json 参考页面中阅读有关每个选项的更多信息
。