Installing Typescript via node, and start using it via VS Code (macOS)
210327
Short Intro
Looking around you will find tons of information about Typescript. According to Wikipedia, “Typescript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs” (https://en.wikipedia.org/wiki/TypeScript).
Besides that, Typescript is the language behind the popular front-end framework Angular, as well as it is widely used also in other front-end frameworks and tools, e.g React, etc.
Some of the features I like in it are that the Typescript adds (optionally) static typing and class-based object-oriented programming.
You can also visit the official Typescript site at: https://www.typescriptlang.org/
Prerequisites
Node/npm
In case you don’t have yet installed Node on your macOS, you can proceed and install it following the instructions here. If you have already done it, you can update it via Homebrew:
$ brew upgrade node
Installation of Typescript
$ npm install -g typescript
We have used the -g flag which means that we have installed it generally. We always can test our installation by checking the version:
$ tsc --version
Furthermore, we can also install the ts-node which is a library that adds a “require hook” to NodeJS that allows us to require and execute TypeScript files directly from a JavaScript file:
➜ ~ ➜ ~ ➜ ~ npm install -g typescript added 1 package, and audited 2 packages in 4s found 0 vulnerabilities npm notice npm notice New minor version of npm available! 7.6.3 -> 7.7.5 npm notice Changelog: https://github.com/npm/cli/releases/tag/v7.7.5 npm notice Run npm install -g npm@7.7.5 to update! npm notice ➜ ~ ➜ ~ tsc --version Version 4.2.3 ➜ ~ ➜ ~ ➜ ~ npm install -g npm@7.7.5 removed 1 package, changed 14 packages, and audited 253 packages in 5s 11 packages are looking for funding run `npm fund` for details found 0 vulnerabilities ➜ ~ ➜ ~ ➜ ~ npm -v 7.7.5 ➜ ~ node -v v15.12.0 ➜ ~ npx -v 7.7.5 ➜ ~ ➜ ~ ➜ ~ ➜ ~ npm install -g ts-node added 10 packages, and audited 11 packages in 2s found 0 vulnerabilities ➜ ~ ➜ ~ ts-node -v v9.1.1 ➜ ~ ➜ ~
Now it’s time to create our 1st project.
Create a new working folder for Typescript projects and then create the classical ‘hello world’ project. Finally, open VS Code and create the helloworld1.ts file:
NB: You can find a tutorial and more info about using VS Code and Typescript at: https://code.visualstudio.com/docs/typescript/typescript-tutorial
➜ ~ ➜ ~ mkdir TypeScriptProjects ➜ ~ cd TypeScriptProjects ➜ TypeScriptProjects ➜ TypeScriptProjects ➜ TypeScriptProjects ➜ TypeScriptProjects mkdir test1 ➜ TypeScriptProjects cd test1 ➜ test1 ➜ test1 code . ➜ test1
Then, using the console view in VS Code, we can compile it to a JavaScript file and then run it via node:
➜ test1 tsc helloworld1.ts ➜ test1 ➜ test1 node helloworld1.js Hello World ➜ test1 ➜ test1
Instead of using the full command:
$ tsc helloworld1.ts
we can create a configuration file. This is quite easy via the tsc –init command (inside our project subfolder):
That, creates a new .json file, the tsconfig.json file. Below is actually what the default tsconfig.json file contains:
{ "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ // "outDir": "./", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ "skipLibCheck": true, /* Skip type checking of declaration files. */ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ } }
After, that we can give just tsc to compile our .ts files. Actually, it finds all the TypeScript files in this folder and compile them.
Moreover, if we want to be a bit more organized, we have to put JavaScript compiled files in a separate subfolder. So, we can modify the tsconfig.ts configuration file by un-commending and adding the appropriate output subfolder at the corresponding line:
like that:
“outDir”: “outputjs”
Thus, next time we will run the compiler, the outputjs subfolder will be created and the compiled files will be placed there.
tsc
Debugging
VS Code has built-in support for TypeScript debugging. To support debugging TypeScript in combination with the executing JavaScript code, VS Code relies on source maps for the debugger to map between the original TypeScript source code and the running JavaScript. We can create source maps during the build by also un-commending the corresponding line “sourceMap”: true in our tsconfig.json.
In order to see the Debugging result in the DEBUG CONSOLE window pane, we have to make the node debugger the active one. With helloworld1.ts open in the editor, press F5. If you have other debugger extensions installed (such as the Chrome Debug extension), you need to select Node.js from the dropdown.
Must install utilities
ts-node
If you have already installed, you can check its version:
➜ test1 ts-node -v v9.1.1 ➜ test1
ts-node is a Node.js package that we can use to execute TypeScript files or run TypeScript in a REPL environment
install: (Global installation:)
npm install -g ts-node
Execute a script as `node` + `tsc`, e.g.:
ts-node myfile.ts
nodemon
nodemon is a tool that helps develop node.js based applications by automatically monitoring changes and restarting the node application when file changes in the directory are detected.
install: (Global installation:)
npm install -g nodemon
➜ test1 npm install -g nodemon added 120 packages, and audited 121 packages in 5s 11 packages are looking for funding run `npm fund` for details found 0 vulnerabilities ➜ test1
Using nodemon:
nodemon myfile.ts
➜ test1 nodemon outputjs/helloworld1.js [nodemon] 2.0.7 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node outputjs/helloworld1.js`
That’s it for now! Have fun with Typescript!
Thank you for reading!