Home  >  Article  >  Web Front-end  >  Detailed explanation of Typescript development node.js project examples

Detailed explanation of Typescript development node.js project examples

小云云
小云云Original
2018-01-26 13:22:052205browse

This article mainly introduces the detailed explanation of using Typescript to develop node.js projects (simple environment configuration). It is of great practical value. Friends in need can refer to it. I hope it can help everyone.

In the process of learning typescript recently, I thought that I might be able to use ts to develop node.js projects. After searching on the Internet, I found that many developers have already practiced this aspect. Here, I record the simple process of setting up my own development environment.

Benefits of using Typescript development:

  • Stricter type checking and syntax checking.

  • It has good support for ES6/ES2015/ES7 (partially).

  • The compiled js file is very clean and supports multiple code specifications.

  • For others, please see the documentation.

Preparation

  • node.js v6.9.1 or any new version, the old version has not been tested yet.

  • tsc typescript compiler, use npm to install: npm install -g typescript, currently v2.0.10

  • Editor: vscode

  • Command line terminal: Windows cmd

Special tips and complaints: Installing tsc may require circumventing the wall (if it is particularly slow), so you can Use Taobao mirror.

Create node.js project

Use npm init to build the project directory in the specified directory.

Here I created a project directory structure of my own:


testTS
|---build         //编译后的js文件目录
|---src          //ts文件目录
|---static        //客户端静态文件
| |---scripts
| |   |---main.js
| |----styles
| |   |---style.css
| |----assets
|---views         //html文件目录
|  |---index.html
|---package.json
|---tsconfig.json

Edit tsconfig.json

There is a tsconfig.json file in the above directory structure, which is used to set the compilation options of ts.

To obtain this file, you can use tsc --init in the project root directory, and a .tsconfig.json will be automatically created.

Write the required configuration items

By default, tsc will use the default compilation configuration to compile all .ts files in the directory. By writing tsconfig.json, we can configure the compilation behavior of tsc to achieve the desired results:


{
  "compilerOptions": {
    "module": "commonjs",  //指定生成哪个模块系统代码
    "target": "es6",    //目标代码类型
    "noImplicitAny": false, //在表达式和声明上有隐含的'any'类型时报错。
    "sourceMap": false,   //用于debug  
    "rootDir":"./src",   //仅用来控制输出的目录结构--outDir。
    "outDir":"./build",   //重定向输出目录。  
    "watch":true      //在监视模式下运行编译器。会监视输出文件,在它们改变时重新编译。
  },
  "include":[
    "./src/**/*"
  ],
  "exclude":[
    "views",
    "static"
  ]
}

Configuration file notes

"compilerOptions" is the compilation option. For details, please see:

Chinese Documentation
English Documentation

"module" is used to specify the settings after compilation js code, which module specification to use. Since we are developing a node.js project, we chose commonjs. (If you are interested, you can try all possible values ​​of all modules and check the differences in the compiled js files. You will find that the generated code is still very good and very clean.)

"target" is Which specification does the compiled js code follow? It can be es3/es5/es6, etc. Here, in order to compare the difference between ts 2.0 code and es6 code, "es6" is used.

"rootDir" is a place that needs attention. It will tell the compiler that the files in this directory need to be compiled. So, what happens if this option is set and a .ts file is placed externally (such as the root directory)? tsc will prompt an error similar to this:

Copy code The code is as follows:


"error TS6059: File 'D:/workplace/nodeWP/testTS/ index.ts' is not under 'rootDir' 'D:/workplace/nodeWP/testTS/src'. 'rootDir' is expected to contain all source files."

And, in the build directory , the output directory structure will also change:

This is obviously not the result we want.

The solution is to use include and exclude attributes. According to the documentation, the "include" and "exclude" attributes specify a list of file glob matching patterns. Indicates the file directories or files that need to be included, and the files or directories that need to be filtered out (you can also use the "files" configuration item, but you need to enter the files one by one. Files explicitly specified by the "files" attribute will always be included. , regardless of how "exclude" is set), see the official documentation for details.

So, add "./src/**/*" to the array pointed to by "include", you can specify all the files under ./src, which we really need to be compiled, and other directories will will be excluded.

"outDir" points to the place where the compiled js code is output. There is also an "outFile" option in the document, which can package all ts files into one file according to certain order rules. Please refer to the document for details. Here, we use outDir first.

Try it out

After writing the two configuration files, you can start writing code and perform compilation. Let’s try it out:

In ./src/server.ts, write a simple paragraph:


interface ICache{
  useCache:boolean;
  [propName:string]:any;
}
const cache:ICache = {useCache:true};

, then enter it in the terminal :

D:\workplace\nodeWP\testTS>tsc

After compilation, server.js will be generated in the build directory:


//server.js
const cache = { useCache: true };

Use .d.ts files

既然要开发一个项目,显然不会只有这些代码。肯定要用到内建模块和第三方模块。然而,直接导入模块,在.ts文件中是不行的。例如:

这是由于typescript自身的机制,需要一份xx.d.ts声明文件,来说明模块对外公开的方法和属性的类型以及内容。感觉有一些麻烦。好在,官方以及社区已经准备好了方案,来解决这个问题。

在TypeScript 2.0以上的版本,获取类型声明文件只需要使用npm。在项目目录下执行安装:


npm install --save-dev @types/node

就可以获得有关node.js v6.x的API的类型说明文件。之后,就可以顺利的导入需要的模块了:


import * as http from 'http';

完成之后,不仅可以正常的使用http模块中的方法,也可以在vscode中获得相应的代码提示。

对于内建模块,安装一个@types/node模块可以整体解决模块的声明文件问题。那么,对于浩如烟海的第三方模块,该怎么办呢?官方和社区中也提供了查找和安装的渠道:

  • typings

  • DefinitelyTyped

  • TypeSearch

自动编译和自动重启服务

解决完了声明文件之后,其实我们已经可以使用ts简单的进行node.js项目的开发了。但是,每次写完或者修改代码,就要编译,然后再启动,是一件不大但是相当让人烦躁的事情。为了效率,我们应当改善它。

首先,要让.ts文件可以自动被编译。这在上文中的tsconfig.json文件中,已经被设置好了,就是"watch":true 。此时在命令行执行tsc命令后,编译器就会时时监控目录中.ts文件的变化,然后自动编译。

自动重启node服务器,我们可以使用 supervisor 模块解决,或者任何具有类似功能的解决方案都可以。

全局安装supervisor模块npm install -g supervisor,之后就可以在终端中使用supervior ./build/server.js启动服务器,并在服务器端代码改变之后,自动重启服务器。

让启动服务更简单

由于以上的2个命令,在启动时都可能需要附加一些参数,每次输入很麻烦。

可以使用npm script来解决。在package.json文件中的"scripts"中,我们设置:


{
  "scripts":{
    "dev": "supervisor -w build ./build/server.js",
    "build": "tsc",
  }
}

执行npm run dev之后,如果./build目录中的.js文件发生改变时,就会重启服务器。

执行npm run build时,则只会编译ts文件并监控ts的改变。

使用例子来试验一下


import * as http from 'http';
//====================
const server = http.createServer(function(request:http.IncomingMessage,response:http.ServerResponse):void{
  console.log("create a server...");
  response.writeHead(200,{'Content-Type':'text/plain'});
  response.write('Hello world,we use typescript to develop.');
  response.end();
});

server.listen(3000,function(){
  console.log("Server listening on port 3000");
  console.log("test...");
});

补充:一个命令实现tsc编译和重启服务器

2017.5.3更新:

感谢大家对本文的支持。有朋友(@Ajaxyz)提出,有没有办法将ts编译监视和重启服务器合并为一个命令?

这里提出一个比较简易的方法,使用gulp来管理这2个流程。(如何使用gulp工作,请参考Gulp API)

1. 使用gulp的watch()来监控ts文件的变化并重启服务器。

这种方式,需要使用gulp和gulp-typescript插件(安装)

注意的一点是:gulp-typescript可能需要在项目的目录安装typescript,所以可以在项目的目录中,运行命令行:


npm install typescript

准备好gulp和插件之后,需要书写一份gulpfile.js作为gulp项目需要执行的任务文件,例子如下:


  //gulpfile.js
  
  let gulp = require('gulp');
  let ts = require('gulp-typescript');
  let tsp = ts.createProject('tsconfig.json'); //使用tsconfig.json文件配置tsc
  let exec = require('child_process').exec;
  
  let child;
  //目录常量
  const PATHS = {
    scripts:['./src/**/*.ts'],
    output:'./build',
  };
  //编译ts文件
  gulp.task('build-ts',['restart'],function(){
    return gulp.src(PATHS.scripts)
      .pipe(tsp())
      .pipe(gulp.dest(PATHS.output));  
  });
  //监视ts文件变化
  gulp.task('watch-ts',['build-ts'],function(){  
    gulp.watch(PATHS.scripts,['build-ts']);
  });
  //自动重启服务器
  gulp.task('restart',function(){
    child = exec('supervisor -w build ./build/server.js',(error,stdout,stderr)=>{
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
      if (error !== null) {
        console.log(`exec error: ${error}`);
      }
    });
  });
  //开发任务
  gulp.task('dev',['build-ts','restart','watch-ts']);

这样,在开发时,直接在项目目录运行gulp dev,就可以启动编译和服务器了。此后,gulp会监视ts文件的改动,然后编译ts文件并重启服务器。刷新页面,就可以看到新结果已经输出在浏览器页面中了。

还有一点需要留意的是,由于gulp负责监视ts文件的变化,因此请在tsconfig.json将"watch"设置为false或者删掉这个属性。

2. 使用tsconfig.json监控ts文件变化并重启服务器

用这种方式,首先打开tsconfig.json对ts文件的监视,然后修改gulpfile.js文件,如下:


  //...requier部分同上面例子,这里省略
  
  let tsChild,    //监视ts文件修改子进程
    serverChild;  //重启服务器子进程
  //编译ts文件
  gulp.task('build-ts',function(){
     tsChild = exec('tsc',(error,stdout,stderr)=>{
      console.log(`tsc====>stdout: ${stdout}`);
      console.log(`tsc====>stderr: ${stderr}`);
      if (error !== null) {
        console.log(`exec error: ${error}`);
      }
    });
  });
  //自动重启服务器
  gulp.task('restart',function(){
    serverChild = exec('supervisor -w build ./build/server.js',(error,stdout,stderr)=>{
      console.log(`restart=====>stdout: ${stdout}`);
      console.log(`restart=====>stderr: ${stderr}`);
      if (error !== null) {
        console.log(`exec error: ${error}`);
      }
    });
  });
  //开发任务
  gulp.task('dev2',['build-ts','restart']);

运行gulp dev2,效果和上一个例子一样。

以上,提供一种解决办法的方式和思路,仅供参考,如果用在实际环境中,还需要进一步完善功能。

结语

本文只是对搭建typescript开发node.js项目的环境做一个简单研究和记录。

最初这样想,也只是好奇可不可以这么做。实际上在node.js稳定版本v6.9.1中已经支持了90%的ES6。因此,直接使用ES6开发node.js项目,是很好的选择。

Sorry for the imperfections, we will add them later.

Related recommendations:

Introducing the declaration types of JavaScript and TypeScript

Share some tips of TypeScript

How to use TypeScript to develop WeChat applet

The above is the detailed content of Detailed explanation of Typescript development node.js project examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn