Search This Blog

Breaking

Friday, 25 June 2021

How to get started with TypeScript in Visual Studio code [Windows]?

If you are planning to start doing coding practice in typescript, then the below steps can help you for doing the initial setup.







1. First, install visual studio (windows installer)

2. Install node (windows installer)

3. Check node --version (visual studio new terminal)

4. Once you have a node, you can use npm. So with the help of it, install typescript globally. 

npm install -g typescript (visual studio new terminal)

5. Check the typescript version to make sure that typescript is installed or not. 

tsc --version

Version 4.3.4

or (You might face this issue)

tsc : File C:\Users\deepak.mathpal\AppData\Roaming\npm\tsc.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

+ tsc --version


tsc.cmd --version


6. To fix the above issue, open powershell with admin (visual studio powersheell does not open with admin access)

provide the access:

Open Commandform : windows + R


Type : Powershell


Then type : set-executionpolicy remotesigned


And select opetion : A


7. now, you can run tsc command. 

tsc --version

Version 4.3.4


8. Create a folder and open it in vscode

C:\Users\deepak.mathpal\Documents>mkdir typescript


C:\Users\deepak.mathpal\Documents>cd typescript


C:\Users\deepak.mathpal\Documents\typescript>code .


C:\Users\deepak.mathpal\Documents\typescript>


9. From the File Explorer, create a new file called helloworld.ts.

let message: string = 'Hello World';

console.log(message);


10. To compile your TypeScript code, you can open the Integrated Terminal (Ctrl+`) and type

 tsc helloworld.ts. 

This will compile and create a new helloworld.js JavaScript file.


11. If you have Node.js installed, you can run node helloworld.js.


12. tsconfig.json


So far, we have been relying on the TypeScript compiler's default behavior to compile our TypeScript source code. We can modify the TypeScript compiler options by adding a tsconfig.json file that defines the TypeScript project settings such as the compiler options and the files that should be included.


Add a simple tsconfig.json which set the options to compile to ES6 and use CommonJS modules.13.


13. {

    "compilerOptions": {

      "target": "es6",

      "module": "commonjs",

      "outDir": "out"

    }

  }

  

  14. add above code in tsconfig file, delete the js file eaerlier created, open a new terminal and run again. Now js file will be inside out directory

  

  15. Run code now from out directory.


References:

1. https://stackoverflow.com/questions/58796490/tsc-ps1-cannot-be-loaded-because-running-scripts-is-disabled-on-this-system

2. https://code.visualstudio.com/docs/typescript/typescript-tutorial








No comments:

Post a Comment