本文将展现如何从0开始初始化一个typescript我的项目。

点击拜访git仓库, 点击下载代码包

初始化

首先,咱们选定一个文件夹,而后在文件夹中执行npm init -y命令来对我的项目进行初始化。

anjie@panjies-Mac-Pro typescript-init % npm init -yWrote 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.json0 directories, 2 files

装置typescript

接下来,咱们应用npm i typescript --save-dev来装置ts

panjie@panjies-Mac-Pro typescript-init % npm i typescript --save-devnpm 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.4added 1 package from 1 contributor and audited 1 package in 2.22sfound 0 vulnerabilities

typescript初始化

ts装置后,咱们也须要一个初始化操作,该操作将默认生成ts的配置文件,对应的命令为npx tsc --init

panjie@panjies-Mac-Pro typescript-init % npx tsc --initCreated a new tsconfig.json with:                                                                                                                            TS   target: es2016  module: commonjs  strict: true  esModuleInterop: true  skipLibCheck: true  forceConsistentCasingInFileNames: trueYou 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.tspanjie@panjies-Mac-Pro typescript-init % node index.jshello world

主动编译运行

每次变更文件化都手动执行一下编译及运行诚然可行,但这种形式确实无法忍受。tsc-watch则专门为此而生,运行npm install tsc-watch --save-dev来装置tsc-watch

panjie@panjies-Mac-Pro typescript-init % npm install tsc-watch --save-devnpm WARN typescript-init@1.0.0 No description+ tsc-watch@5.0.3added 20 packages from 16 contributors and audited 21 packages in 3.788sfound 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