Developing Node.js Program with TypeScript

Time:2019-6-24

Translator: Crazy Technology House
Original: https://medium.com/@freek_men…


Wechat Public Number: Front-end Pioneer
Welcome to pay attention and push you fresh front-end technology articles every day


When I first discovered TypeScript, I used it in my own JavaScript program. There are many benefits to using TypeScript, and now you need to give me a convincing reason to write anything in native JavaScript.

In this article, I’ll show you how to set up a simple development environment to write Node. JS applications using TypeScript.


First, there may be a thousand or more different ways to create Node. JS programs in TypeScript. I just want to show you the way I like it.

In addition, you can find my entry project here: https://github.com/toxsickcod…. There are some additional features that will not be discussed in this article.

Package.json

As I said before, there are many ways to do this. I like to use Webpack for TypeScript projects. But the first thing to do is to create apackage.jsonStart.

You can use it.npm initCommand Generationpackage.jsonYou can also copy and paste the following code and make changes.

// package.json
{
  "name": "node-typescript",
  "version": "0.0.1",
  "author": "Freek Mencke",
  "homepage": "https://medium.com/@freek_mencke",
  "license": "MIT",
  "scripts": {},
  "dependencies": {},
  "devDependencies": {}
}

Let’s start with a simple Webpack configuration for the JavaScript Node.js project. After the basic settings are completed, TypeScript will be added.

program

As mentioned earlier, we’ll start with JavaScript programs and convert them to TypeScript later. First, create a band withmain.jsandinformation-logger.jsDocumentarysrc/Directory, which contains some Node.js functions:

// src/information-logger.js
const os = require('os');
const { name, version} = require('../package.json');
module.exports = {
  logApplicationInformation: () =>
    console.log({
      application: {
        name,
        version,
      },
    }),
  logSystemInformation: () =>
    console.log({
      system: {
        platform: process.platform,
        cpus: os.cpus().length,
      },
    }),
};
// src/main.js
const informationLogger = require('./information-logger');
informationLogger.logApplicationInformation();
informationLogger.logSystemInformation();

This script will output some system information to the console. Functionnode main.jsAfter that, you can see the following output:

{ application: { name: 'node-typescript', version: '0.0.1' } }
{ system: { platform: 'linux', cpus: 8 } }

Webpack

Before using Webpack, the first thing you need to do is install the necessary dependencies. Don’t forget to use it-DLogo, which represents devDependencies.

npm i -D webpack webpack-cli

You may notice that I did not install it.webpack-dev-server。 This is because we are creating a Node.js application. I’ll use it later.nodemonIt has the same purpose.

webpack.config.js

The next step is to create awebpack.config.jsFile, which tells Webpack how to handle our code.

// webpack.config.js
'use strict';
module.exports = (env = {}) => {
  const config = {
    entry: ['./src/main.js'],
    mode: env.development ? 'development' : 'production',
    target: 'node',
    devtool: env.development ? 'cheap-eval-source-map' : false,
  };
  return config;
};

As you can see, starting with Webpack doesn’t require much configuration. The only two options you need areentryandtarget。 We useentryThe field declares the entry point of the program and tells Webpack to use it in Node. JStargetFields.

Can be usedmodeThe field tells Webpack whether it should focus on compilation speed (development) or obfuscation and shrinkage (production). To help debug, you need to run in development mode, usingdevtoolField to indicate that we want source mapping. In this way, if an error occurs, it can be easily found in the code where it occurs.

To use Webpack, you need to create some NPM commands:

// package.json
...  
  "scripts": {
    "start": "webpack --progress --env.development",
    "start:prod": "webpack --progress"
  },
...

Now you can build programs by running these commands. It will create a directorydist/It contains the output filemain.js。 You can specify a different name with output configuration in webpack. config. js.

Our project should now be like this:

dist/
  main.js
node_modules/
src/
  information_logger.js
  main.js
package-lock.json
package.json
webpack.config.js

nodemon

You may have noticed that after running the startup command, Webpack stops after the application is built. It does not monitor the changes we make to the files. Because we’re using Node.js, we can’t use it.webpack-dev-server

Fortunately, it can be used.nodemonTo solve this problem. It is a tool developed specifically for this purpose: restarting Node.js applications during development.

Let’s start with the installationNodemon-webpack-plugin starts。 Don’t forget it-DLogo, because it is a dev Dependency.

npm i -D nodemon-webpack-plugin

Let’s create a new onenodemonLogo and add plug-ins towebpack.config.jsMedium.

// webpack.config.js
'use strict';
const NodemonPlugin = require('nodemon-webpack-plugin');
module.exports = (env = {}) => {
  const config = {
    entry: ['./src/main.js'],
    mode: env.development ? 'development' : 'production',
    target: 'node',
    devtool: env.development ? 'cheap-eval-source-map' : false,  
    resolve: { // tells Webpack what files to watch.
      modules: ['node_modules', 'src', 'package.json'],
    },   
    plugins: [] // required for config.plugins.push(...);
  };
  if (env.nodemon) {
    config.watch = true;
    config.plugins.push(new NodemonPlugin());
  }
  return config;
};

When we pass the nodemon flag, we need to set up WebpackwatchConfig, and addnodemonPlug-in unit. When we change the file, WebpackwatchConfig will rebuild the program.nodemonThe plug-in will restart the program after the rebuilding is completed.

We also need to update the NPM command. I also created some not yet.nodemonLogo construction command,.

// package.json
...
  scripts: [
    "start": "webpack --progress --env.development --env.nodemon",
    "start:prod": "webpack --progress --env.nodemon",
    "build": "webpack --progress --env.development",
    "build:prod": "webpack --progress",
    "build:ci": "webpack"
  ],
...

We have completed the basic Webpack settings for the Node.js program. The next step is to add TypeScript!

TypeScript

Now let’s add TypeScript! First install the required dependencies.

Since this is a Node.js project, we also need to install related support. I’m working on the LTS version of Node.js, which is version 10. This is my installation.^ 10.0.0Reasons for the edition.

npm i -D typescript ts-loader @types/[email protected]^10.0.0

ts-loader

We will usets-loaderWebpack plug-ins compile TypeScript.

We need toentryFile suffix changed to.tsAnd tell webpack that it must also be parsed.tsFiles (By default, Webpack only works for.jsDocumentation).

// webpack.config.js
...
  const config = {
    entry: ['./src/main.ts'],
    mode: env.development ? 'development' : 'production',
    target: 'node',
    devtool: env.development ? 'cheap-eval-source-map' : false,
    resolve: {
      // Tells Webpack what files to watch      
      extensions: ['.ts', '.js'],
      modules: ['node_modules', 'src', 'package.json'],
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          use: 'ts-loader',
        },
      ],
    },
    plugins: [], // Required for config.plugins.push(...);
  };
...

tsconfig.json

If we try to run our program now, it will crash. Because the tsconfig. JSON file is still missing. So create one first.

// tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": ["dom", "es2018"],
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "removeComments": true,    
    "resolveJsonModule": true,
    "strict": true,
    "typeRoots": ["node_modules/@types"]
  },
  "exclude": ["node_modules"],
  "include": ["src/**/*.ts"]
}

As shown above, I prefer strict tsconfig files, which you don’t have to do. I like to set high grammatical versions of my target code(esnextores2018Because Node.js supports the new JavaScript functionality very well.

program

We still need to extend the JavaScript file from.jsChange to.ts。 Let’s do this and try to run the project.

After running the project, you can immediately see that we made a “mistake” in the test application we created. We can’t do it in package. JSONnameFields are deconstructed because they may have been defined or we override them. So we need to make some changes.

// information-logger.ts
import os from 'os';
import { name, version } from '../package.json';
export class InformationLogger {
  static logApplicationInformation(): void {
    console.log({
      application: {
        name,
        version,
      },
    });
  }
  static logSystemInformation(): void {
    console.log({
      system: {
        platform: process.platform,
        cpus: os.cpus().length,
      },
    });
  }
}
// main.ts
import { InformationLogger } from './information-logger';
InformationLogger.logApplicationInformation();
InformationLogger.logSystemInformation();

If you follow all the previous steps, the project structure should now be as follows:

dist/
  main.js
node_modules/
src/
  information-logger.ts
  main.ts
package-lock.json
package.json
tsconfig.json
webpack.config.js

We are ready to write Node.js programs in TypeScript!

Final Notes

I’m sure there are thousands of different ways to write Node. JS applications in TypeScript. What I’m writing about is not the way you have to do it, it’s just one way you can do it.

The remaining steps may be to add TSLint integration, add Docker file, set up CI pipeline… Everything is in your hands.


Wechat Public Number: Front-end Pioneer

Welcome to scan the two-dimensional code, pay attention to the public number, and push you fresh front-end technical articles every day.

Developing Node.js Program with TypeScript


Welcome to continue reading other highly praised articles in this column:

  • Twelve amazing CSS pilot projects
  • Fifty React Interview Questions Must Be Meet
  • What do top companies in the world ask in front-end interviews?
  • 11 Best JavaScript Dynamic Effect Libraries
  • CSS Flexbox Visualization Manual
  • React from the Designer’s Perspective
  • Is the festival boring? Write a brain game in JavaScript.
  • How does CSS sticky positioning work
  • Step by step teach you how to use HTML5 SVG to achieve animation effect
  • Programmers earn less than 30K a month before they are 30 years old. Where to go?
  • 14 Best JavaScript Data Visualization Libraries
  • Eight top-level VS Code extension plug-ins for the front end
  • Complete guide to Node.js multithreading
  • Four Solutions and Implementation of Converting HTML to PDF