Learn TypeScript 3 by Building Web Applications
上QQ阅读APP看书,第一时间看更新

Adding TypeScript to the project

Now that you're more familiar with npm, let's add TypeScript to our project. As discussed in the last section, we'll add it to the package.json  file and then we will also add a script to invoke it easily.

First, add the devDependencies section and add TypeScript to those dependencies (since TypeScript is a tool and is only necessary at build time):

"devDependencies": {
"typescript": "3.4.4" },
As we've already mentioned before, you can search for npm packages on the official website: https://www.npmjs.com. In the case of TypeScript, the package is located here: https://www.npmjs.com/package/typescript.

Next, replace the scripts section with the following:

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

With this script, we will be able to easily invoke the TypeScript version that we have now added to our project. This will avoid issues in case you (or someone else working on the project) have another version of TypeScript installed globally.

Now that your package.json file is ready, you can go ahead and install the project dependencies using npm install:

$ npm install 

npm notice created a lockfile as package-lock.json. You should commit this file. 
npm WARN todoit-v1@1.0.0 No description 
npm WARN todoit-v1@1.0.0 No repository field.  

added 1 package from 1 contributor and audited 1 package in 1.213s
found 0 vulnerabilities 

Now you should have a node_modules folder with TypeScript inside as well as tsc binary under node_modules/.bin. You should also have the package-lock.json file.

If you look into it, you'll see that it lists all of the dependencies (including transitive ones), along with an exact version:

{ 
  "name": "todoit-v1", 
  "version": "1.0.0", 
  "lockfileVersion": 1, 
  "requires": true, 
  "dependencies": { 
    "typescript": { 
      "version": "3.4.4", 
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-
3.4.4.tgz",
"integrity": "sha512-xt5RsIRCEaf6+j9AyOBgvVuAec0i92rgCaS3S+UVf5Z
/vF2Hvtsw08wtUTJqp4djwznoAgjSxeCcU4r+CcDBJA==",
"dev": true } } }
As you can see,  npm  keeps tracks of the exact version that it has installed for us. You can actually get the same result with npm install typescript --save-dev. That command will add the dependency to the devDependencies section for you automatically and then install the package directly.

At this point, you should be able to execute the TypeScript compiler by running the tsc script, using npm run compile:

$ npm run compile 

> todoit-v1@1.0.0 tsc C:\dev\wks\tsbook\assets\2\todoit-v1 
> tsc 

Version 3.4.4 
Syntax:   tsc [options] [file...​] 
...​

For now, TypeScript doesn't yet know what to do for us, which brings us to the next point: tsconfig.json.