Detailed explanation using TypeScript development Node.js project (simple environment configuration)

Recently, in the process of learning TypeScript, you can use TS to develop Node.js projects. Search online, in fact, many developers have practiced this aspect. Here, I record the simple process of building a development environment.

Use TypeScript development benefits:

More stringent type checks and syntax checks.
  • It is better to support ES6 / ES2015 / ES7 (part).
  • The compiled JS file is clean and supports a variety of code specification.
  • Other, see the documentation.
  • Preparation

Node.js v6.9.1 or any new version, the old version has no experimentation. TSC TypeScript compiler, use NPM installation: npm install -g typescript, currently V2.0.10

Editor: vscode
  • command line terminal: Windows CMD
  • Special tips and spit: Installing TSCs may need to turn over the wall (if particularly slow), you can also use Taobao mirror.
  • Establish Node.js Project
Using npm init in the specified directory to build a directory.

Here I have established a project catalog structure:

TESTTS | — Build // Compile JS File Directory | -src // TS file directory | — static // client static file | | — scripts | | — main.js | |Les | | | — style.css | | —- assets | — views // html file directory | | — index.html | — package.json | — tsconfig.json

Edit Tsconfig.json

There is a TSCONFIG.JSON file in the top of the top, used to set TS Compile option.
 Want to get this file, you can use TSC -init in the project root directory, you will automatically create a good .tsconfig.json.   Writing required configuration items 
By default, TSC uses all .ts files in the directory using the default compilation configuration. By writing tsconfig.json, we can configure the compilation behavior of TSC to achieve the result:


{“compilerOptions”: {“Module:” Commonjs “, / / Specify which module system code “Target”: “ES6”, // Target code type “noimumitiTany”: false, // In the expression and declaration, there is an implicit “Any ‘type when there is an implicit” Any’ type. “SourceMap”: false, // Used for Debug “rootdir”: “./ src”, // only to control the output directory structure –outdir. “Outdir”: “./ build”, // redirect output directory. “Watch”: true // Run the compiler in the monitor mode. The output file will be monitored and recompiled when they change. }, “incluDE “: [” ./src/**/** “],” Exclude “: [” Views “,” static “]}


configuration file Notes

“CompileROptions” is a compilation option. For details, see:

Chinese document

English document

” “Is it used to specify the setup JS code, what module specification is used. Since developed Node.js project, choose Commonjs. (If you are interested, you can try all the Module all possible values, view compilation The difference in JS file will find that the generated code is still very good, very clean.)
  "Target" is what specification with the compiled JS code, which can be ES3 / ES5 / ES6, etc. Here, in order to compare the TS 2.0 code and the ES6 code, "ES6" is used.  
“Rootdir” is where you need to pay attention, it will tell the compiler, and the files in this directory need to compile. Then, if this option is set, it is placed outside (such as root directory). How about it? TSC will prompt a mistake 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 / TESTS / SRC ‘.’ Rootdir ‘Is Expected To Contain All Source Files. “

And, in the catalog of build, the output directory structure also changes:

This is obviously not what we want.

The solution is to use the include and Exclude properties. Follow the document description, “include” and “Exclude” properties Specify a file GLOB matching mode list. Indicates the file directory or file you need to include, and the file or directory you need to filter (you can also use the “Files” configuration item, but you need a file entry, “files” attribute is explicitly specified, but it is always included. No matter how “Exclude” is set.), See the official document description for details.

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

“Outdir” points to the place where the compiled JS code is output. There are also “outfile” options in the document that all TS files can be packaged into a file in accordance with certain order rules, and can be referred to the documentation. Here, we prefer Outdir.

Test

After writing 2 configuration files, you can start writing code and compiled. We trial:
In ./src/server.ts, write a simple step:



Interface icache {usecache: boolean [PROPNAME: STRING]: Any;} const cache: True = {usecacache: true};

, entries in the terminal:

D: \ Workplace \ NodeWP \ TESTTTS> TSC 详解使用Typescript开发node.js项目(简单的环境配置)

Generates Server.js to BuildIn the directory:

// server.jsconst cache = {usecache: true};

is used .d. TS file

Since it is necessary to develop a project, it is obvious that only these code will be only available. There must be built-in modules and third-party modules. However, importing modules directly, can’t work in .ts file. For example:

This is due to the mechanism of TypeScript itself, requires a XX.D.TS declaration file to explain the method and content of the module’s external publication method and attribute. I feel some troubles. Good, official and communities have prepared a plan to solve this problem.

In TypeScript 2.0 or more, the acquisition type declaration file only needs to use NPM. Perform the installation in the project directory:

NPM INSTALL –SAVE-DEV @ Types / Node
   
Get Type Description of the API of Node.js v6.x. After that, the required module can be improved:

Import * AS HTTP from ‘http’;


After completion, it is possible not only to normalize the method in the HTTP module, but also get the corresponding code prompt in VSCode.
For built-in modules, install a @ Types / Node module can solve the problem of modules in the overall declaration file problem. So, what should I do for the third-party module of the Haozihai? The official and communities also provide the channels of finding and installation:
   Definitelytyped 


详解使用Typescript开发node.js项目(简单的环境配置)

After completing the declaration file, we can use TS simple to perform Node. The development of the .js project. However, each time you write or modify the code, you must compile, then start, it is a matter of not big but quite annoying. For efficiency, we should improve it.

First, let the .ts file can be automatically compiled. This is already set in the tsconfig.json file above, is “Watch”: true. At this point, after the command line executes the TSC command, the compiler will monitor the change in the directory in the directory, and then automatically compile.

Automatically restart the Node server, we can use the Supervisor module to resolve, or any solution with similar functions can be used.
Global Install Supervisor Module NPM Install -G Supervisor, then you can use the supervior ./build/server.js to start the server in the terminal, and automatically restart the server after the server-side code change.
  Make the startup service is simpler  
Due to the above two commands, there may be additional parameters at startup, which is cumbersome each time.

Can be solved using NPM Script. In “scripts” in the package.json file, we set:

 {"Scripts": {"dev": "Supervisor -w Build ./build/Server .js "," build ":" TSC ",}}   After the NPM RUN DEV is executed, if the .js file in the .js file is changed.When it is restarted. 
When performing NPM RUN Build, only the TS file is compiled and the change of TS will be monitored.

  • Import * as http from ‘http’; // ==== ================ Const server = http.createserver (Request: http.incomingmessage, response: http.serverResponse): void {console.log (“Create a Server .. “); response.writehead (200, {‘content-type’: ‘text / place’}); 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 … “);});

Supplement: One command implements TSC compilation and restart server

2017.5.3 Update:

Thank you for your support. Have a friend (@ajaxyz), is there a way to compile TS compilation and restart the server into a command?

A relatively simple method is proposed, using Gulp to manage these 2 processes. (How to use Gulp work, please refer to Gulp API)

1. Use Gulp’s Watch () to monitor the change of the TS file and restart the server.

This way, it is necessary to use GULP and GULP-TYPEScript plug-in (installation)

Note that gulp-typescript may need to install TypeScript in the directory of the project. So in the project’s directory, run the command line:

NPM Install TypeScript

 Prepare Gulp and plug-ins After that, you need to write a task file that gulpfile.js as a GULP project requires execution, as follows:   
//gulpfile.js let gulp = request (‘gulp’) Leet Ts = Require (‘Gulp-TypeScript’); Let TSP = Ts.createProject (‘tsconfig.json’); // Use the Tsconfig.json file to configure TSC Let EXEC = Require (‘Child_Process’). EXEC; Let Child ; // directory constant const paths = {scripts: [‘./ src / ** / *. Ts’], output: ‘./ build’,}; // Compile TS file Gulp.Task (‘build-ts’ [‘RESTART’], FUNCTION () {Return Gulp.src (Paths.Scripts) .pipe (TSP ()) .pipe (gulp.dest (path.output));}; // Monitor TS file changesGulp.Task (‘Watch-Ts’, [‘Build-Ts’], Function () {Gulp.watch (Paths.Scripts, [‘Build-Ts’]);}); // Auto Restart server Gulp.task (‘restart’, function () {childvisor -w build ./build/server.js’, (error, stdout, stderr) => {Console.log (`stdout: $ {stdout}`) Console.log (`stderr: $ {stderr}`); if (Error! == Null) {Console.log (`EXEC ERROR: $ {Error});}});}}); // Develop task Gulp.task (‘dev’, “‘Watch-Ts’, ‘Restart’, ‘Watch-Ts’]);

In this way, it is directly The project directory runs Gulp DEV, you can start compilation and servers. Thereafter, GULP monitors the change of the TS file, then compile the TS file and restart the server. Refresh the page, you can see that the new result has been output in the browser page.

There is also something to pay attention to that because Gulp is responsible for monitoring the change of the TS file, please set “Watch” to false or delete this property in Tsconfig.json. 2. Use TSConfig.json to monitor TS file changes and restart the server

Use this way, first open Tsconfig.json’s monitoring of TS files, Then modify the gulpfile.js file as follows:
  ///...Requier part With the above example, omitted Let Tschild, // Monitor TS file modifier sub-process serverchild; // Restart the server sub-process // Compile TS File 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} `);}}) ;}); // Automatically restart server 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}`);}});}); // Develop task gulp.task ('dev2', ['build-ts', 'restart']);  "
Run the Gulp DEV2, the effect is the same as the previous example.

The above, providing a solution and ideas for a solution, for reference only, if used in the actual environment, further improvement is needed.

This article is only a simple study and record on the environment that develops TypeScript development Node.js project.

I thought I thought I couldn’t be so curious. Actually, 90% of ES6 has been supported in Node.js Stability Version V6.9.1. Therefore, it is a good choice to use the ES6 development node.js project.

Improper place, please forgive me, will be added slowly.

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment