0%

typescript-tsc-guide

Install TypeScript

This directive will install TypeScript globally.

1
npm install -g typescript

Init TypeScript project

This step will create a tsconfig.json file in under typescript-tsc-guide folder.

1
2
3
mkdir typescript-tsc-guide
cd typescript-tsc-guide
tsc --init # create tsconfig.json file

Create typescript files

Create a folder src under current folder. Then create a file index.ts under src folder.

1
2
mkdir src
touch src/index.ts

input the following code to src/index.ts file.

1
const add = (a, b) => a + b;

Compile TypeScript files

This step will compile the src/index.ts file to src/index.js file.

1
2
cd typescript-tsc-guide
tsc

Compile options

outDir

Usually, we put the emitted files under dist folder. To do this, we need to modify the tsconfig.json file.

1
2
3
4
5
{
"compilerOptions": {
"outDir": "./dist" // output directory for the emitted files
}
}

Run tsc again, the emitted files will be under dist folder.

rootDir

We can also specify the source folder by using rootDir option, in this way, only files under the source folder will be compiled.

1
2
3
4
5
6
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src" // specify the source folder
}
}

If you specify the rootDir option, you can’t put the source files outside the source folder. otherwise you’ll got the following error:

1
error TS6059: File '/typescript-tsc-guide/xxx.ts' is not under 'rootDir' '/typescript-tsc-guide/src'. 'rootDir' is expected to contain all source files.

To test this, create a file test.ts under project root(same location as tsconfig.json) and run tsc command, you’ll get the error.