本文将展现如何从 0 开始初始化一个 typescript
我的项目。
点击拜访 git 仓库, 点击下载代码包
初始化
首先,咱们选定一个文件夹,而后在文件夹中执行 npm init -y
命令来对我的项目进行初始化。
anjie@panjies-Mac-Pro typescript-init % npm init -y
Wrote to /Users/panjie/github/yunzhiclub/typescript-init/package.json:
{
"name": "typescript-init",
"version": "1.0.0",
"description": "","main":"index.js","scripts": {"test":"echo \"Error: no test specified\" && exit 1"},"repository": {"type":"git","url":"git+https://github.com/yunzhiclub/typescript-init.git"},"keywords": [],"author":"",
"license": "ISC",
"bugs": {"url": "https://github.com/yunzhiclub/typescript-init/issues"},
"homepage": "https://github.com/yunzhiclub/typescript-init#readme"
}
该命令将为咱们生成一个 package.json
文件:
panjie@panjies-Mac-Pro typescript-init % tree
.
├── README.md
└── package.json
0 directories, 2 files
装置 typescript
接下来,咱们应用 npm i typescript --save-dev
来装置ts
:
panjie@panjies-Mac-Pro typescript-init % npm i typescript --save-dev
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN typescript-init@1.0.0 No description
+ typescript@4.6.4
added 1 package from 1 contributor and audited 1 package in 2.22s
found 0 vulnerabilities
typescript 初始化
ts 装置后,咱们也须要一个初始化操作,该操作将默认生成 ts 的配置文件,对应的命令为npx tsc --init
panjie@panjies-Mac-Pro typescript-init % npx tsc --init
Created a new tsconfig.json with:
TS
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
You can learn more at https://aka.ms/tsconfig.json
该命令将为咱们主动生成tsconfig.json
,如果你想进行一些定制,则只须要关上此文件,找到对应的项进行批改或启用即可。
index.ts
根本的初始化工作实现后,便能够创立index.ts
,并进行代码的测试了。
'use strict';
const hello = (world: string) => {console.log(`hello ${world}`);
}
hello('world');
编译运行
文件创建实现后进行编译及运行:
panjie@panjies-Mac-Pro typescript-init % npx tsc index.ts
panjie@panjies-Mac-Pro typescript-init % node index.js
hello world
主动编译运行
每次变更文件化都手动执行一下编译及运行诚然可行,但这种形式确实无法忍受。tsc-watch 则专门为此而生,运行 npm install tsc-watch --save-dev
来装置tsc-watch
:
panjie@panjies-Mac-Pro typescript-init % npm install tsc-watch --save-dev
npm WARN typescript-init@1.0.0 No description
+ tsc-watch@5.0.3
added 20 packages from 16 contributors and audited 21 packages in 3.788s
found 0 vulnerabilities
装置实现后,咱们关上 package.json
文件,在 scripts
中减少以下 dev
项:
"scripts": {
"test": "echo \"Error: no test specified\"&& exit 1",
"dev": "tsc-watch --noClear -p ./tsconfig.json --onSuccess \"node ./index.js\""
},
而后咱们在命令行中运行 npm run dev
则能够实现:当文件变更时从新编译、从新运行的目标。
参考文档
- https://www.digitalocean.com/community/tutorials/typescript-new-project
- https://www.npmjs.com/package/tsc-watch