Introduction to the
Typescript has become a must-have skill for front-end developers. It makes up for many javascript defects, has static type checking, ide intelligent prompts, and greatly improves the readability of code. Wouldn’t it be better if it could be integrated into Node project development? I’ll show you how to integrate quickly.
Complete code -> Github
Basic steps
Local Project Name
mkdir typescript-node
cd typescript-node
Copy the code
Initialization package. Json
npm init -y
Copy the code
Install typescript as a development dependency because when we deploy Node, we compile TS to JS to perform the deployment.
npm i typescript -D
Copy the code
All TS projects must set the configuration file tsconfig.json in the root directory. We can automatically generate some basic Settings
tsc --init --rootDir src --outDir dist
Copy the code
There are also some necessary Settings
{" compilerOptions ": {" module" : "commonjs / / specifies which module system generated code" esModuleInterop ": true," allowSyntheticDefaultImports ": True, "target": "es6", // Object code type "noImplicitAny": true, // An error occurs when there is an implied 'any' type on expressions and declarations. "ModuleResolution ": "node", "sourceMap": true, // for debug "outDir": "dist", // only for control of output directory structure "baseUrl": "."}, "include": ["src/**/*"] }Copy the code
Install express
npm i express
Copy the code
Install the necessary typescript @Type type definitions so you can use them directly in your project,
With TS-Node, you can execute typescript files directly without compiling them. There are many NPM packages with types, DefinitelyTyped, provided by the TS community
This time you need to install the NPM package
npm i -D @types/node @types/express nodemon ts-node
Copy the code
Create the SRC directory and create the files
mkdir src
cd src
touch index.ts handlers.ts
Copy the code
Handlers. Ts code is as follows:
import { Request, Response } from 'express';
interface HelloResponse {
hello: string;
}
type HelloBuilder = (name: string) = > HelloResponse;
const helloBuilder: HelloBuilder = name= > ({ hello: name });
export const rootHandler = (_req: Request, res: Response) = > {
return res.send('typescript & node is working');
};
export const helloHandler = (req: Request, res: Response) = > {
const { params } = req;
const { name = 'World' } = params;
const response = helloBuilder(name);
return res.json(response);
};
Copy the code
The index.ts code is as follows:
import express from 'express';
import { rootHandler, helloHandler } from './handlers';
const app = express();
const port = process.env.PORT || '8000';
app.get('/', rootHandler);
app.get('/hello/:name', helloHandler);
app.listen(port, err= > {
if (err) return console.error(err);
return console.log(`Server is listening on ${port}`);
});
Copy the code
Process.env. PORT does not report errors due to the introduction of the @types/node package
Add the run script to package.json
"scripts": {
"dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
"build":"tsc",
"start":"node dist/index.js"
}
Copy the code
use
Local development automatically builds NPM Run Dev
Compile and deploy NPM run build/NPM run start