The typescript+react of Nodejs ecological Circle

Source: Internet
Author: User

An introductory tutorial on Typescript+react development based on Nodejs ecological circle

    1. Overview

This tutorial is intended to provide introductory explanations for front-end program development based on the Nodejs NPM ecosystem.

    1. What is Nodejs?

Nodejs is a high-performance JavaScript scripting environment, built on the chrome V8 scripting engine. It is equivalent to extracting the functionality of JavaScript scripts in the browser, as a separate program that can be used in environments such as the desktop command-line.

    1. What is NPM?

NPM is the Nodejs Pack Manager (Nodejs Package Manager) and is now the largest open source scripting repository in the world. It manages thousands of script libraries. It also provides a toolkit that can be executed in the NODEJS environment, providing us with the ability to download the class library from the repository and to upgrade and unload the class library.

    1. Eco-Circle

There are many classes of libraries and tools available in NPM.

But we should choose between these tools and the class library. The following tools or class libraries are used in this tutorial.

    1. Environment construction
      1. Installing NODEJS&NPM

We first download the Nodejs installation package from Nodejs official website nodejs.org, to choose the corresponding version (X86/X64) with your system.

Installation is all the way next.

When we choose to install the components, we can see that the Nodejs running core in the option is necessary because you need it to run the script.

Of course the installer also integrates NPM, and we need it to download and manage the class libraries and toolkits, both of which we need.

Add to path this is to add the NPM package path to the system path, this is also very important, often we use NPM installed a tool, we need to directly invoke the tool in the CMD command line, then this option is required.

After the installation is complete, we can make a simple test to enter node into the Nodejs running environment in CMD.

Then enter a script to see the execution.

    1. Use vs Code

Here we use a simple code editor vs code, rather than a powerful IDE like vs. Our ability to abandon vs these powerful Ides is only a more in-depth understanding of the various tools needed to build the front-end development mechanism. We downloaded the installation package from the VS Code website and opened it directly after installation.

We create a new empty project folder, open in VS code, we can use the shortcut key ctrl+~ to quickly open the cmd command line in this directory.

    1. Using NPM

We typed the NPM init command at the command line. This command creates the NPM package profile Package.json in the project directory, which defines the various modules required for this project, as well as the configuration information for the project (such as name, version, license, and so on).

We can use the default settings, and eventually the project root will generate a configuration file in the following format.

The above configuration gives us a partial complement to the generated basic configuration file.

Let's explain the usefulness of the common configuration fields in Package.json:

    • The Main:main field specifies the entry file that the project loads. If you want to reference our project externally as a module class library, the first one executes will be the portal file. The default entry file name is called Index.js.
    • The Scripts:scripts field configures script commands that can be run using NPM run XX. For example, with a TSC command configured above, we can invoke the NPM run TSC to execute this command. The start command is a built-in command in the scripts system, meaning that we can launch our project by invoking NPM start.
    • The Dependencies:dependencies field specifies the module on which the project is run.
    • The Devdependencies:devdependencies field specifies the module to be relied upon when the project is developed, and the dependencies field points to a class library and tool. The class library or tool includes a name and a corresponding version.

Because Systemjs and react are the class libraries we need to run the project, we put him in dependencies.

Because Lite-server and concurrently are the tools we need to develop, we put him in the devdependencies. Lite-server is a lightweight HTTP server at development time (equivalent to the functionality provided by IIS), concurrently is a library of functions that can execute Package.json scripts scripts in parallel.

Now that the project has been configured, the class libraries and scripts to be relied on have been added to the configuration file. We now need to download and install the class libraries or tools we rely on to use in our projects.

When the NPM install command executes, the dependencies defined in our Package.json file are automatically installed. The packages installed from here are installed locally, which means that the installed dependencies are automatically placed in the Node_modules folder in the local project root directory.

NPM Install once we've installed our Package.json configured class libraries and tools, we'll also need to use both typescript and typings tools. And now we need to install both tools into the global catalog.

We run in the command line:

NPM install–g typescript

NPM install–g typings

NPM installs both packages into the global catalog, and NPM installs in two locations: 1. Add-g,2 to the global catalog parameter. In the local directory

Once the installation is complete, we can use the TSC command provided by the Typescript Software library to compile the TS code into JS and use typings to download the d.ts definition files for public class libraries that are not written in TS language.

    1. Replace NPM Warehouse Source

Because NPM is associated with our domestic network abroad, it may be too slow to download the package from the repository in NPM install. So we can cut NPM warehouse source into our domestic server, we can switch by the following command.

NPM Config Set Registry https://registry.npm.taobao.org

    1. React and Typescript
      1. React Introduction

React is a front-end MVVM framework that enables front-end development to be more modular and facilitates the maintenance and sharing of front-end controls.

React and NPM are not necessarily connected. It simply publishes its own code package in the NPM repository, making it easy for users to download and install via NPM, which can also be used by other packages that can be run in the NODEJS environment.

React several major mechanisms:

    • Component of

      React advocates the development of a front-end UI with component thinking, by splitting the parts of the UI into components and assembling them when they are used, so that a single function is clear and more conducive to code reuse and later maintenance.

    • Virtual DOM

      To achieve high performance and cross-platform features for Dom control, react adds a layer of virtual DOM to the HTML real DOM. When we operate on the DOM, the operation performs a comparison calculation in the virtual DOM layer, finds the DOM elements that really need to be modified, and modifies the real HTML DOM, which greatly reduces the number and frequency of modifications to real DOM elements, thus improving performance.

    • State-driven, one-way data binding

      React changes to DOM elements are always driven by the state of the component. When state data within a component is modified, react automatically calculates the DOM that needs to be modified for modification. and data binding is one-way, that is, when the user modifies the value of the page DOM element, and does not directly reverse the impact of the state data within the component, only when the corresponding event is bound to this DOM element, through this event to trigger the state of the change, you can update the state value within the component.

    • JSX syntax

      JSX syntax is a syntactic sugar that allows you to write HTML code directly into JavaScript scripts and mix HTML and JavaScript code together. As follows:

      In fact, it eventually passes through the compilation, after which the JavaScript script code is still being translated. As follows:

    1. Typescript Introduction

TYPESCIPRT is a scripting language, which is an enhanced version of JavaScript that extends JavaScript's class libraries and adds object-oriented features. Of course, its greatest feature is the compatibility of JavaScript, which compiles its own code into JavaScript code.

We configured it as a development-time tool to be used in our project, and its main purpose was to compile typescript into JavaScript code with its TSC command.

Typescript some of the extensions to JavaScript:

    • Class
    • Enum enum
    • Interface interface
    • <T> generics
    • Namespace namespaces

For example, we develop a class and use inheritance, as follows:

    1. Start using

We now use the two together, we develop a simple component, named: hellocomponent

First we create the hellocomponent.tsx file in the scripts directory under our project. A typescript script code file that uses the JSX syntax is internal to the TSX file description file.

Then we add the following code:

Finally, the effect in the browser is as follows:

Let's make a general explanation of this code:

First we use import to refer to the React class library

Then we write a component of our own hellocomponent, this component needs to inherit the React.component component class. This class is a generic class <tp,ts> a generic parameter needs to pass in two types: TP is the attribute type interface for this component, and TS is the state type interface for this component. TP defines the properties that can be passed in to a component when it is called externally. TS defines what fields the internal state of the component will have.

We write the HTML element code that our component needs to present in the Reder method, We have bound the This.state.text field in the display text of the value and span of input, where the contents of these two places are changed as soon as State.text has changed.

The question now is how we can modify our state data. Here we first initialize the default state in the component's constructor. State.text uses an externally passed-in component property Inittext value. Next we bind the onchange event in input, and when this event is triggered, we also modify the value of the State.text as the input control. In this way, the modification of the State.text is achieved, and the modification function of the interface display is achieved.

Typescript at compile time we need to configure it, we add the Tsconfig.json file in the project root directory, add the following configuration code in the file:

Let's take a general look at the meanings of the fields in this configuration:

    • Compileonsave: Enable compiling TS to JS when saving TS, TSX files
    • Target:ts compiled to the target version of JS, we generally use ES5, easy to do browser-compatible
    • Module:ts compiled to JS using the module mode, module mode has a variety (COMMONJS, AMD, etc.), we use the Nodejs of the modular organization method COMMONJS
    • Moduleresolution:ts the way to find modules, with node and default lookups. Configure the TS module as node meaning typescript can be found from the node_modules.
    • ALLOWJS: Whether to support the identification of JS as TS module
    • JSX: Specifies the way in which the TSX compiles the typescript file with the JSX syntax when it is compiled to JS, where we choose react, because we need to compile the JSX syntax into react JavaScript code.

OK, typescript configuration file We have configured OK, we directly execute the TSC command at the command line to compile the TSX into a JS code file.

At compile time, we found that the compilation error, the module react is not found.

Because react is not written in TS language, and it does not provide a D.TS definition profile, TS does not recognize it as a module. Here we need to add a d.ts file for it to allow TS to recognize it.

Here's the turn of the Typings tool. The purpose of the Typings tool is to download the appropriate d.ts definition files for public class libraries that are not written in TS language. It has multiple data sources and can be downloaded from a variety of locations to find the D.ts file we need for the class library.

With the typings search react command, we can see that the d.ts files associated with react exist in a number of data sources. Here we prefer to download from the DT data source.

We typed in the command line:

This command typings installs react into our project from the DT data source.

--GLOBAL Specifies that this REACT.DT.S will be referenced as our project global definition and will be installed in the project root directory typings\globals directory.

--SAVE specifies that the installation will be logged to the Typings configuration file, Typings.json. After the installation is complete, we will see that typings automatically generated this file for us in the project root directory.

React the definition file we have installed, now we are going to execute the TSC compiler command. This compilation sees no error prompting and generates a hellocomponent.js file in the hellocomponent.tsx current directory.

    1. Load Run

React components We have developed, now we need to put it in HTML to show it. And when using hellocomponent.js, we can have a variety of options to reference it. Instead of using the <script> tag to put it in HTML directly, we use the SYSTEMJS module resource loader to load it.

There are several reasons for this:

    • In the TS configuration is generated by the Commonjs module JS, so put it directly into the <script> tag reference to the HTML will not recognize require and other methods.
    • The SYSTEMJS module loader, which can load the modules we need on demand, is a good solution to the dependency between modules.

First we add index.html to our project root directory, the code is as follows:

We use the <script> tag directly in HTML to refer to JS files only System.js and system.config.js. When we use system.js, we need some configuration to let it know the composition of our project and so on.

The configuration code for System.config.js is as follows:

We have configured the react and react-dom libraries we use, as well as the Require method. Detailed descriptions of the options in the configuration are required to be viewed in the SYSTEMJS official documentation, which we do not explain in detail here.

Okay, now that everything is ready, we execute NPM start on the command line. Since we have configured the following script command in Package.json's scripts.

So NPM will execute tsc–w for us (this command is TS can open all TS files in the monitoring project, if there are changes, it will recompile) and lite HTTP server.

After the Lite HTTP server starts, it listens to a port and automatically opens a page in our browser.

The components shown on the page are the Hellocomponent components we developed. Now we can start writing more components and assemble and use them.

This tutorial provides an introductory basic tutorial for the front-end development react+typescript based on the Nodejs eco-environment, and the tutorial covers the REACT,TYPESCRIPT,SYSTEMJS and other knowledge that the tutorial just made a general overview. In future development, we also need to gain a deeper understanding of them through a variety of channels.

The typescript+react of Nodejs ecological Circle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.