Get the App
SLTechnology News&Howtos  ›  Development  › 

How to develop TypeScript by VSCode

Shulou Source: shulou.com Published: 2022-06-01 13:21:54 09月22日 Update

This article introduces the relevant knowledge of "how to develop TypeScript by VSCode". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

TypeScript is a superset of JaveScript and adds a lot of features to JavaScript. It can be compiled into pure JavaScript and run on browsers. TypeScript has become the first choice for all kinds of popular frameworks and front-end application development.

The first program

To develop TypeScript in VS Code, first install TypeScript, which is installed here using npm:

Npm install typescript-g

After the installation is complete, run the following code to see the version:

Tsc-version

Go to the console, create a folder, enter this folder, and run the command code. This starts VS Code and opens the current folder. Create a file hello.ts in the folder and write a few lines of code:

Let v = "hello"; console.log (v)

Enter the console, type tsc hello.ts, will generate the corresponding hello.js, enter node hello.js, will run the code.

Profile tsconfig.json

Now let's create the configuration file tsconfig.json for the TypeScript project. The simplest content is as follows:

{"compilerOptions": {"target": "es5", "module": "commonjs"}}

VSCode's smart tips are helpful when editing this file. Other common settings include: the output path of js code, whether it can include js files, the code mapping used when debugging, and so on. Here are some more complex configurations:

{"compilerOptions": {"target": "es5", "module": "commonjs", "allowJs": true, "sourceMap": true, "outDir": "out"}}

Here the output path is set to out. We delete the js file generated by the previous compilation and recompile it. Note that since you have the tsconfig.json file, you only need to enter tsc in the terminal.

As you can see, the compiled files are saved in the out subdirectory with more map files.

Debug

Now let's see how to debug in VS Code. In the previous ts code interface, press F5 to debug, there will be a prompt box to select the environment, select Node.js, and the following error occurs:

Select "configure Task", and then select "tsc: build-tsconfig.json". At this point, a new folder .vscode will be created, and a task.json will be created in this folder, as follows:

{"version": "2.0.0", "tasks": [{"type": "typescript", "tsconfig": "tsconfig.json", "problemMatcher": ["$tsc"] "group": "build", "label": "tsc: build-tsconfig.json"]}

Press F5 again and the above error still occurs. Selecting add configuration creates a "launch.json" file:

{"version": "0.2.0", "configurations": [{"type": "node", "request": "launch", "name": "startup program", "skipFiles": ["/ *"] "program": "${workspaceFolder}\\ helloworld.ts", "preLaunchTask": "tsc: build-tsconfig.json", "outFiles": ["${workspaceFolder} / out/**/*.js"]}]}

Press F5 again, there will still be an error, check, you will find that the generated two files, the name of the task is not the same, change the "tsc: build-tsconfig.json" in task.json to "tsc: build-tsconfig.json", press F5 to run again, this time is fine. Try to add a breakpoint, or you can:

Modularization

We want to modularize our code and split the code into separate files to facilitate separate development and debugging. We want to declare references explicitly to avoid confusion caused by global variable functions, and so on. At this point, we need to use export to declare functions and variables that can be used by other modules, and in modules that use these functions and variables, use import to import required functions, variables, and so on. Let's create a new file, myfunctions.ts, with only one function:

Export function myName () {return "Zhang San";}

Modify helloworld.ts and call this function:

Import {myName} from'. / myfunctions'let v = "hello" + myName (); console.log (v); package client code using Webpack

The first few parts are aimed at server-side development, for the client-side code, we hope that 1) can be packaged as a separate js file for release; 2) you can easily run the client program; 3) you can easily debug. Here we use Webpack as a packaging tool to create a client project skeleton for TypeScript in VS Code.

First, create a directory for our test project, enter it on the console, and run code. Exe. Start vs code. Execute npm init in the terminal, and create the packeg.json of the project, as follows:

{"name": "mydevnew", "version": "1.0.0", "description": "my new typescript project", "main": "index.js", "scripts": {"test": "echo\" Error: no test specified\ "& exit 1"}, "author": "", "license": "ISC"}

Then, install the necessary packages and execute in the terminal:

Npm install-save-dev webpack webpack-cli typescript ts-loader webpack-dev-server source-map-loader

Next, add the configuration file tsconfig.json for typescript:

{"compilerOptions": {"module": "es6", "target": "es5", "sourceMap": true, "declaration": true, "declarationDir": ". / dist/typing", "lib": ["webworker", "es6", "es5", "dom"]} "exclude": ["node_moudles", "dist"]}

Also add webpack.config.js:

Const path = require ('path') Module.exports = {mode: 'development', entry:'. / src/main.ts',// entry file output: {filename: 'main.js',// compiled file name path: path.resolve (_ _ dirname,' dist'), / / directory where the compiled file is located, publicPath:'/ dist/',// static resource directory, which can be set to "directory where the compiled file is located" Automatic code compilation Automatic page refresh}, module: {rules: [{/ / For our normal typescript test: /\ .ts? $/, use: [{loader: 'ts-loader'}] Exclude: / (?: node_modules) /,},]}, resolve: {modules: ['src',' node_modules'], extensions: ['.js', '.ts']} DevServer: {static: {directory: path.join (_ _ dirname,''),}, hot: true, compress: true, host: 'localhost', port: 8888}, devtool:'source-map',}

Modify package.json by adding the following to scritps:

"build": "webpack", "dev": "webpack-dev-server"

At this point, the configuration environment is basically complete, and you can write code. Create a src directory to save the code, and create main.ts and hello.ts in src, as follows:

Import {myName} from "hello" console.log ("TypeScript Test Project"); console.log (myName ()); document.Boy [XSS _ clean] = "Hello!" + myName ()

Hello.ts is a small module:

Export function myName () {return "Zhang San";}

Create a boot page index.html in the root directory:

TypeScript test project

At this point, we can run npm run dev in the terminal, start the web server of webpack, type http://localhost:8888 in the browser, and you can see that it is ready to run:

If you just want to compile, run npm run build, generate the js file and save it in the dist directory, where index.html is the boot page.

This is the end of "how VSCode develops TypeScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: File code run compile development directory configuration function folder project content module selection variable client program terminal creation generation input Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi macOS Shulou Tech Info MariaDB Apple