preface

Many times, after learning something new, we don’t know how to apply what we have learned to the project. This article aims to use Node.js + TypeScript + Express to implement a simple backend server, in order to further understand the application of TS in practical development.

Basic knowledge of

Here’s what you need to know before reading this column:

  1. Basic knowledge of JavaScript;
  2. Understand Node.js and Express framework;
  3. Learn the basics of TypeScript for TypeScript overview.

Project initialization

  1. Create a project folder simple-login-node and go to the folder.
  2. Go to the project folder and initialize the project with NPM init, TSC –init, and tsLint –init. Before initialization, make sure NPM, typescript, and tsLint are installed globally.
npm install -g npm
npm install -g typescript
npm install -g tslint
Copy the code
  1. Create the app.ts file in the/SRC directory under the root directory.

After doing this, our directory structure is as follows:

/src/app.ts // Program entry file
.npmrc // Project NPM configuration file, which can be set separately for the project
package.json // Project module description file
tsconfig.json // typescript configuration files
tslint.json // tslint configuration file
Copy the code

That’s the basic structure of a node.js project written in typescript. Let’s break it down further. What are the important configurations for each configuration?

package.json

  • Scripts configuration instruction set, when we use NPM run *, * represents the instructions that we configure under the script node.
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
}
Copy the code

NPM run test: echo “Error: no test specified” && exit 1

  • NPM install –save *
  • DevDependencies NPM install –save-dev * installs packages in development mode only. Because typescript only checks code at compile time, that is, only at development time, many Typecript-related modules and third-party modules with declaration files are installed only in development mode. Install the express module and run it in the project root directory:
npm install --save express // Install the normal Express module and generate the package record under Dependencies
npm install --save-dev @types/express // Install the Express module with the declaration file and generate the package record under devDependencies.
Copy the code

At this point, package.json looks like this (only the key code is attached) :

"dependencies": {
  "express": "^ 4.17.1"
},
"devDependencies": {
  "@types/express": "^ 4.17.0"
}
Copy the code

tsconfig.json

If a tsconfig.json file exists in a directory, it means that the directory is the root of the typescipt project. Tsconfig. json defines the root directory and compilation options used to compile the project. Let’s take a look at some of the key configuration items.

{
  /* Compiler options */
  "compilerOptions": {
    "target": "es6".// Specify the target version of EECMAScript, for this we use ES6
    "module": "commonjs".// Specify which module of the system code to compile to generate, for compatibility purposes, we set this to commonJS
    "outDir": "dist".// Compile the output directory, that is, the output directory after the.ts file is compiled into the.js file. Set this to the /dist directory in the root directory
    "strict": true.// Strict mode
    "noImplicitAny": false.// There is an error with an implied any type on expressions and declarations. Set to false to avoid errors when type inference is any
    "moduleResolution": "node".// Decide what to do with the module. Set to the node
    "baseUrl": ". /".// Define the root directory for the TS project. This must be set before setting Paths
    // Define the path alias, that is, when we import a module through the path, we can use the alias to import it. The first * is set to import third-party modules; The second '@/*' is for direct and quick import of modules under/SRC.
    "paths": {
      "*": ["node_modules/*"."src/types/*"]."@ / *": ["src/*"]}"esModuleInterop": true // Module import mode
  },
  "include": ["src"].// The ts files to compile, set this to all files in the SRC directory
  "exclude": ["node_modules"] // Compile the directory of files to exclude
}
Copy the code

tslint.json

The tsLint configuration file is used to check whether the code conforms to the specified code specification, and will prompt an error if it does not, see the source code at the end of this article for details.

Setting up the Express Service

  1. Install the Body-Parser module to handle the request body of POST requests
npm install --save body-parser
Copy the code
  1. / SRC/config/index.ts/index.ts/index.ts/index.ts/index.ts/index.ts/index.ts/index.ts
const systemConfig = {
  port: 8000};export default {
  systemConfig,
};
Copy the code
  1. This is a typescript project. We try to define the type of the systemConfig variable in the configuration. We create a types directory under/SRC to store all the project’s type definitions, and a config.ts file under /types. The type is defined and introduced in the configuration file
// /src/types/config.ts
export interface ISystemConfig {
  port: number;
}

// /src/config/index.ts
import { ISystemConfig } from "@/types/config";

const systemConfig: ISystemConfig = {
  port: 8000};Copy the code

This limits the systemConfig object to a single property, port, of type number, and will prompt code for internal properties when using systemConfig. 4. Create the Express service under/SRC /app.ts

// Third party module
import bodyParser from 'body-parser';
import express from 'express';
import { NextFunction, Request, Response } from 'express'; // Express declares the type defined by the file

// Custom module
import { systemConfig } from './config';

const app = express();

// The request body that handles POST requests, with a maximum size of 20 megabytes
app.use(bodyParser.urlencoded({ limit: '20mb'.extended: true }));
app.use(bodyParser.json({ limit: '20mb' }));

// error handler
app.use(function(err: Error, req: Request, res: Response, next: NextFunction) {
  return res.sendStatus(500);
});

app.listen(systemConfig.port, function() {
  console.log(`the server is start at port ${systemConfig.port}`);
});

export default app;
Copy the code

Project running

So we’re done. Let’s try it out

node ./src/app.ts
Copy the code

But.. Grammar mistakes

tsc
Copy the code

Json, we set the output directory of the compiled JS code to be the /dist directory. After executing the command, we can see that the /dist directory is generated under the root directory.

A problem

Do we have to recompile every update and then start the service?

The solution

The Nodemon and TS-Node are installed to monitor the CHANGES of TS codes in the specified directory. After the changes, the project is automatically compiled and run.

// Only development environment installation
npm install --save-dev nodemon // Nodemon monitors any changes in the Node.js application and automatically restarts the service
npm install --save-dev ts-node The ts-node command executes TypeScript source files directly without prior compilation
Copy the code

After the installation is complete, we use Nodemon to monitor the changes of all TS files under/SRC. When the changes occur, we use TS-Node to directly re-app.ts. The command is as follows:

nodemon --watch 'src/' -e ts --exec 'ts-node' ./src/app.ts
Copy the code

According to theten_noc< div style = “box-sizing: border-box; word-break: break-word! Important;”

cross-env nodemon --watch 'src/' -e ts --exec 'ts-node' ./src/app.ts
Copy the code

To optimize the

As you can see, the above startup command is a bit long. Is it unfriendly to type such a long list every time? So is there a way to simplify? There are! Remember earlier that you can configure startup scripts in package.json!

// Add dev configuration to script tag"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."dev": "nodemon --watch 'src/' -e ts --exec 'ts-node' ./src/app.ts"
  }
Copy the code

Then we can just run NPM run dev to start the project and see what happens

Summary and source code

This article is a simple construction of a Typecript express service. I am also learning about typescript. If there are any shortcomings, please point them out in the comments section. If you find it helpful, don’t forget to like it and follow it.