[TypeScript] Introduction and detailed steps for environment construction

The Encounter of TypeScript

Although we already know what TypeScript does and what kind of problems it solves, we still need to fully understand what TypeScript is?

Get to know TypeScript

Let's take a look at TypeScript's definition of itself on GitHub and the official website :

GitHub说法: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

TypeScript官网: TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

These two places mean the same thing, translated: TypeScript is a typed superset of JavaScript that compiles into plain, clean, and complete JavaScript code.

How to understand the above words?

We can think of TypeScript as an enhanced version of JavaScript .

TypeScript supports all the features of JavaScript, and it follows ECMAScript standards, so ES6, ES7, ES8 and other new syntax standards are supported;

And at the language level, it not only adds type constraints, but also includes some syntax extensions , such as enumeration types (Enum), tuple types (Tuple), etc.;

While implementing new features, TypeScript always keeps pace with or even leads the ES standard;

And TypeScript will eventually be compiled into JavaScript code, so you don't need to worry about its compatibility, and you don't need to resort to tools like Babel when compiling;

Therefore, we can understand TypeScript as a more powerful JavaScript, which not only makes JavaScript more secure, but also brings many useful and useful features to it;

TypeScript Features

The official description of the characteristics of TypeScript, I think it is very good (although some official, understand it), let's share it together

Begins with JavaScript, Belongs to JavaScript

TypeScript started with syntax and semantics familiar to millions of JavaScript developers today. Use existing JavaScript code, including popular JavaScript libraries, and call TypeScript code from JavaScript code;

TypeScript can compile pure and concise JavaScript code, and can run on any browser, Node.js environment and any JavaScript engine that supports ECMAScript 3 (or later);

TypeScript is a powerful tool for building large projects

Types allow JavaScript developers to use efficient development tools and common operations such as static checking and code refactoring when developing JavaScript applications;

Types are optional, and type inference lets some type annotations make a big difference in the static validation of your code. Types let you define interfaces between software components and gain insight into the behavior of existing JavaScript libraries;

Has advanced JavaScript

TypeScript provides the latest and evolving JavaScript features, including those from ECMAScript 2015 and future proposals, such as async functions and Decorators, to help build robust components;

These features are available when developing high-confidence applications, but will be compiled into concise ECMAScript3 (or newer) JavaScript;

It is because of these features that TypeScript is currently used in many places :

Angular source code was rewritten using TypeScript very early, and developing Angular also requires mastering TypeScript;

The Vue3 source code is also rewritten using TypeScript. When reading the source code, we saw a lot of TypeScript syntax;

Including the most popular editor, VSCode, is also done using TypeScript;

Including the ant-design UI library that has been used in React, it is also heavily written in TypeScript;

At present, the development mode of Vue3+TypeScript and React+TypeScript is very popular in the company;

Including applet development, it also supports TypeScript;

Big front-end development trend

At present, we have more and more things to learn at the front end, learning various frameworks, and now we have to learn TS

When the author of node was developing a new framework deno in 2018, someone once submitted such an issue on GitHub

insert image description here

The big front-end is a group of developers who can or need to toss the most :

Client-side developers: From Android to iOS, or from iOS to Android, to RN, more and more client-side developers are now exposed to front-end related knowledge (Vue, React, Angular, applet);

Front-end developers: From jQuery to AngularJS, to three parallel frameworks: Vue, React, Angular, and small programs, and even some front-end development now also need to contact client-side development (such as RN, Flutter);

At present, we are facing not only learning new features such as ES6, 7, and 8, but also learning TypeScript;

With the emergence of new frameworks, we need to learn the features of new frameworks, such as vue3.x, react18, etc.;

But the appearance of every technology will be surprising, because it must solve a pain point of the previous technology, and TypeScript really solves many design flaws in JavaScript, especially about type detection .

And from the long-term perspective of developers, learning TypeScript helps us front-end programmers to cultivate type thinking, which is especially important for completing large-scale projects .

TypeScript environment


TypeScript compilation environment

As we mentioned earlier, TypeScript will eventually be compiled into JavaScript to run, so we need to build the corresponding environment :

We need to install TypeScript on the computer, so that it can be compiled into JavaScript through TypeScript's Compiler;

insert image description here

TypeScript code cannot run directly on the browser, it needs to be compiled into JavaScript code to run on the browser, so who needs to complete this compilation process?

There are two tools that can help us convert:

  1. tsc: TypeScript Compiler
  2. babel: There is a preset plugin in babel

Currently we use the official tsc tool

First, we need to install globally through npm :

Installation command:npm install typescript -g

View version:tsc --version

[Demo] The use of tsc, for example, we write some TS code

insert image description here

Type the command in the terminal:tsc 文件名

After the input is completed, a js code with the same name will be generated

Then run the js code in the browser or node environment.

insert image description here

TypeScript runtime environment

It would be too cumbersome if we had to go through these two steps every time in order to see the running effect of the TypeScript code :

Step 1: Compile TypeScript to JavaScript code through tsc;

Step 2: Run the JavaScript code in the browser or Node environment;

Is it possible to simplify such steps?

For example, after writing TypeScript, can it run directly on the browser?

For example, after writing TypeScript, execute it directly through the command of node?

The two ways I mentioned above can be done with two solutions :

Method 1: Through webpack, configure the local TypeScript compilation environment and start a local service, which can run directly on the browser;

Method 2: Provide an execution environment for TypeScript to run through the ts-node library, ts-node will do two things: help you compile; help you run in node;


Method 1: webpack configuration

In the project, Vue-cli will automatically help us configure the TS environment. In some special cases, we also need to configure it ourselves

Note: You may need some simple understanding of npm and webpack here, it will not be very complicated (if you don't understand at all, just follow the steps I gave, and then add some knowledge yourself)

Step 1: Initialize the package.json file via npm :npm init

After the input is complete, press Enter to all

Step 2: Install webpack and webpack-cli locally :npm install webpack webpack-cli -D

add a script in package.json

insert image description here

  • Create a webpack.config.js file
const path = require('path')

module.exports = {
    
    
  mode: "development",
  entry: "./src/main.ts",
  output: {
    
    
    path: path.resolve(__dirname, "./dist"),
    filename: "bundle.js"
  }
}

Step 3: Install ts-loader and typescript :npm install ts-loader typescript -D

Reason for local installation:

  • Because we then compile our TypeScript code through webpack, not through tsc. (tsc uses the globally installed TypeScript dependencies)
  • Then webpack will look for TypeScript dependencies locally, so we need to rely on TypeScript locally;
  • Then configure the matching rules in the webpack.config.js file
const path = require('path')

module.exports = {
    
    
  mode: "development",
  entry: "./src/main.ts",
  output: {
    
    
    path: path.resolve(__dirname, "./dist"),
    filename: "bundle.js"
  },
  resolve: {
    
    
    extensions: [".ts"]
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.ts$/,
        loader: 'ts-loader'
      }
    ]
  }
}

Step 4: Initialize the tsconfig.json file :tsc --init

A tsconfig.json file will be automatically generated, and the ts file can be compiled into a js file at this time

Step 5: Build a local server :npm install webpack-dev-server -D

After installation, configure a script in package.json

insert image description here

  • We also need an index.html as a template

insert image description here

  • Install npm install html-webpack-plugin -Dthe configuration template in webpack.config.js, and the final configuration in webpack.config.js is as follows
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    
    
  mode: "development",
  entry: "./src/main.ts",
  output: {
    
    
    path: path.resolve(__dirname, "./dist"),
    filename: "bundle.js"
  },
  devServer: {
    
    
  },
  resolve: {
    
    
    extensions: [".ts", ".js", ".cjs", ".json"]
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.ts$/,
        loader: 'ts-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: "./index.html"
    })
  ]
}

At this point, the main.ts file we wrote directly will run directly on the browser

insert image description here

insert image description here


Method 2: Install ts-node

Installation command:npm install ts - node -g

Installation command:npm install ts - node -g

In addition, ts-node needs to rely on two packages, tslib and @types/node, which also need to be installed:npm install tslib @types/node -g

Now, we can run TypeScript code directly through ts-node:ts - node 文件名

insert image description here

In the grammar learning of TS, I will use the second method, and I will use the first method in the follow-up projects.

Guess you like

Origin blog.csdn.net/m0_71485750/article/details/126318928