Let’s summarize the basic tasks to be set while starting an express project using typescript in vscode.

VSCode extension to install

First, install’ESLint’ and’Prettier’ in VSCode.

-ESLint: https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint -Prettier: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode

ESLint helps you identify grammatical errors or anti-patterns in JavaScript code and create consistent code styles. Originally, TSLint was called Lint for TypeScript, but since last year (2019), it was integrated and operated as’ESLint`.

Prettier is a tool that automatically corrects/cleans up codes according to established rules. Various languages ​​are supported.

Express Basic Setup

First, create a package.json file through npm init.

npm init -y

And install express.

npm install express

After installation is complete, install typescript and @types/express.

npm install --save-dev typescript @types/express

Packages starting with @types are packages whose data type is set in TypeScript, which is useful when checking the type in the source code and autocomplete in vscode.

Create a ./src folder and create an app.ts file and enter it as below.

./src/app.ts

import * as express from'express';
const app = express();
const port = process.env.PORT || 3000;

app.get('/', (req: express.Request, res: express.Response) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}!`);
});

Install ts-node-dev.

npm install -D ts-node-dev

ts-node-dev is similar to ts-node so that .ts can be executed immediately without compiling the JavaScript file. In addition, when the file is changed, it helps to re-execute and debug through inspect.

Then, to execute the file, add the following to the scripts section of the package.json file.

{
  // ...
  "scripts": {
    "dev": "ts-node-dev --inspect --watch - ./src/app.ts"
  },
  //...
}

---inspect: Used for debugging in vscode. ---watch: If the source code is modified, it is reloaded. ---: Put the file to run after. It is used when there is an option on the front.

If the execution environment is set as above, you can execute it as below.

npm run dev

Connect to the address of http://127.0.0.1:3000 from a web browser and check if the connection is successful.

Configuring tsconfig.json file

To use TypeScript in a project, you need to set TypeScript through a file called tsconfig.json. You can create the file yourself and put it in, but you can also set it through the tsc command.

npx tsc --init

Contains most of the specifications of the tsconfig.json file. In order to simply use express, you only need to set it as shown below.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5", /* ECMAScript version of the file to be created after compilation */
    "module": "commonjs", /* Module version used by the file to be generated after compilation */
    "outDir": "dist/", /* Folder where files will be created */
    "esModuleInterop": true /*'require' and'import' compatible */
  },
  "include": ["src/*.ts"] /* Folders and files to use */
}

However, if you want to use other packages and decorations of type script, etc., it is recommended to set as below.

tsconfig.json

{
  "compilerOptions": {
    "lib": ["es2016","esnext.asynciterable"], /* Libraries to be included in the compilation */
    "types": ["node"], /* list of names to contain type definitions */
    "target": "es2016", /* ECMASCript version of the target */
    "module": "commonjs", /* specify module code generation */
    "moduleResolution": "node", /* How to interpret the module */
    "outDir": "./dist", /* output directory */
    "strict": true, /* enable strict type checking option */
    "emitDecoratorMetadata": true, /* Send design-type metadata for decorator declaration to source */
    "experimentalDecorators": true, /* enabled for ES decorators */
    "sourceMap": true, /* Use Source Map */
    "allowSyntheticDefaultImports": true, /* Allow default imports from modules without default export */
    "esModuleInterop": true, /*'require' and'import' compatible */
    "skipLibCheck": true, /* Omit type checking of all declaration files (*.d.ts) */
    "resolveJsonModule": true, /* Include modules imported with .json extension */
  },
  "include": [
    "./src/**/*",
  ],
  "exclude": [
    "node_modules",
    "src/test",
    "**/*.spec.ts",
    "**/*.test.ts",
  ]
}

If you set up the settings like this and run tsc, you can see that the source is compiled and executed in the dist folder.

npx tsc

VSCode debugging settings

If there is no .vscode folder, create a folder and enter ./.vscode/launch.json file as below.

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/src/app.ts",
      "preLaunchTask": "npm: build",
      "env": {
        "SRC_PATH": "dist/"
      },
      "sourceMaps": true,
      "smartStep": true,
      "internalConsoleOptions": "openOnSessionStart",
      "outFiles": [
        "${workspaceFolder}/dist/**/*.js"
      ]
    },
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to Inspector",
      "protocol": "inspector",
      "port": 9229,
      "cwd": "${workspaceRoot}"
    }
  ]
}

Now click in front of the row where you want to breakpoint or press the’F9’ key and you will see a red circle in front of the row.

Debugging Settings

Select the debug menu on the left or press the Ctrl+Shift+D key to move to the debug menu, select Launch Program and press the F5 button. You can check the status of.

Alternatively, after running the program with npm run dev in the terminal, select Attach to Inspector from the debug menu and press F5 to debug from the middle without running it individually. Send feedback History Saved Community