博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
报纸打字项目_如何使用打字稿设置节点项目
阅读量:2509 次
发布时间:2019-05-11

本文共 10813 字,大约阅读时间需要 36 分钟。

报纸打字项目

介绍 (Introduction)

is a environment that makes it possible to write server-side . It has gained widespread adoption since its release in 2011. Writing server-side JavaScript can be challenging as a codebase grows due to the nature of the JavaScript language; and .

是一个环境,可以编写服务器端 。 自2011年发布以来,它已被广泛采用。由于JavaScript语言的特性,随着代码库的增长,编写服务器端JavaScript可能会面临挑战。 和 。

Developers coming to JavaScript from other languages often complain about its lack of strong static typing, but this is where TypeScript comes into the picture, to bridge this gap.

从其他语言开始使用JavaScript的开发人员经常抱怨它缺乏强大的静态类型,但这正是TypeScript进入图片的地方,以弥合这种差距。

is a typed (optional) super-set of JavaScript that can help with building and managing large-scale JavaScript projects. It can be thought of as JavaScript with additional features like strong static typing, compilation, and object oriented programming.

是JavaScript的类型化(可选)超集,可帮助构建和管理大型JavaScript项目。 可以将其视为具有附加功能JavaScript,例如强大的静态类型,编译和面向对象的编程。

Note: TypeScript is technically a super-set of JavaScript, which means that all JavaScript code is valid TypeScript code.

注意: TypeScript从技术上讲是JavaScript的超集,这意味着所有JavaScript代码都是有效的TypeScript代码。

Here are some benefits of using TypeScript:

这是使用TypeScript的一些好处:

  1. Optional static typing.

    可选的静态类型。
  2. Type inference.

    类型推断。
  3. Ability to use Interfaces.

    使用界面的能力。

In this tutorial you will set up a Node project with TypeScript. You will build an application using TypeScript and transpile it down to neat and reliable JavaScript code.

在本教程中,您将使用TypeScript设置Node项目。 您将使用TypeScript构建应用程序,并将其转换为整洁而可靠JavaScript代码。

先决条件 (Prerequisites)

Before you begin this guide, you will need Node.js installed on your machine. You can accomplish this by following the guide for your operating system.

在开始本指南之前,您需要在计算机上安装Node.js。 您可以按照操作系统的“ 指南来完成此操作。

第1步-初始化npm项目 (Step 1 — Initializing an npm Project)

To get started, create a new folder named node_project and move into that directory.

首先,创建一个名为node_project的新文件夹并移至该目录。

  • mkdir node_project

    mkdir node_project

  • cd node_project

    cd node_project

Next, initialize it as an npm project:

接下来,将其初始化为npm项目:

  • npm init

    npm初始化

After running npm init, you will need to supply npm with information about your project. If you’d rather let npm assume sensible defaults, then you can add the y flag to skip the prompts for additional information:

运行npm init ,您将需要向npm提供有关您的项目的信息。 如果您想让npm假定为合理的默认值,则可以添加y标志以跳过提示以获取其他信息:

  • npm init -y

    npm初始化-y

Now that your project space is set up, you are ready to move on to install the necessary dependencies.

既然已经设置了项目空间,那么就可以继续安装必需的依赖项了。

第2步-安装依赖项 (Step 2 — Installing Dependencies)

With a bare npm project initialized, the next step is to install the dependencies that are required to run .

初始化一个裸露的npm项目之后,下一步是安装运行所需的依赖项。

Run the following commands from your project directory to install the dependencies:

从项目目录运行以下命令以安装依赖项:

  • npm install -D typescript@3.3.3

    npm install -D typescript@3.3.3
  • npm install -D tslint@5.12.1

    npm install -D tslint@5.12.1

The -D flag is the shortcut for: --save-dev. You can learn more about this flag .

-D标志是--save-dev的快捷方式。 您可以了解有关此标志 。

Now, it is time to install the framework:

现在,该安装框架了:

  • npm install -S express@4.16.4

    npm install -S express@4.16.4
  • npm install -D @types/express@4.16.1

    npm install -D @ types / express @ 4.16.1

The second command installs the Express types for TypeScript support. Types in TypeScript are files, normally with an extension of .d.ts. The files are used to provide type information about an API, in this case the Express framework.

第二个命令安装Express 类型以支持TypeScript。 TypeScript中的类型是文件,通常以.d.ts扩展名。 这些文件用于提供有关API(在本例中为Express框架)的类型信息。

This package is required because TypeScript and Express are independent packages. Without the @types/express package, there is no way for TypeScript to know about the types of Express classes.

由于TypeScript和Express是独立的软件包,因此需要此软件包。 没有@types/express包,TypeScript无法了解Express类的类型。

第3步-配置TypeScript (Step 3 — Configuring TypeScript)

In this section, you will setup TypeScript and configure linting for TypeScript. TypeScript uses a file called tsconfig.json to configure the compiler options for a project. Create a tsconfig.json file in the root of the project directory and paste in the following snippet:

在本节中,您将设置TypeScript并配置TypeScript的linting。 TypeScript使用一个名为tsconfig.json的文件来配置项目的编译器选项。 在项目目录的根目录中创建一个tsconfig.json文件,并粘贴以下代码段:

tsconfig.json
tsconfig.json
{  "compilerOptions": {    "module": "commonjs",    "esModuleInterop": true,    "target": "es6",    "moduleResolution": "node",    "sourceMap": true,    "outDir": "dist"  },  "lib": ["es2015"]}

Let’s go over some of the keys in the JSON snippet above:

让我们来看一下上面的JSON代码片段中的一些键:

  • module: Specifies the module code generation method. Node uses commonjs.

    module :指定模块代码生成方法。 节点使用commonjs

  • target: Specifies the output language level.

    target :指定输出语言级别。

  • moduleResolution: This helps the compiler figure out what an import refers to. The value node mimics the Node module resolution mechanism.

    moduleResolution :这可以帮助编译器弄清楚导入是指什么。 值node模仿节点模块解析机制。

  • outDir: This is the location to output .js files after transpilation. In this tutorial you will save it as dist.

    outDir :这是在编译后输出.js文件的位置。 在本教程中,您将其另存为dist

An alternative to manually creating and populating the tsconfig.json file is by running the following command:

手动创建和填充tsconfig.json文件的另一种方法是运行以下命令:

  • tsc --init

    tsc --init

This command will generate a nicely commented tsconfig.json file.

此命令将生成一个注释良好的tsconfig.json文件。

To learn more about the key value options available, the official offers explanations of every option.

要了解有关可用键值选项的更多信息,官方提供了每个选项的说明。

Now you can configure TypeScript linting for the project. In a terminal running in the root of your project’s directory, which this tutorial established as node_project, run the following command to generate a tslint.json file:

现在,您可以为项目配置TypeScript棉绒。 在项目目录根目录中运行的终端(本教程将其建立为node_project ,运行以下命令以生成tslint.json文件:

  • ./node_modules/.bin/tslint --init

    ./node_modules/.bin/tslint --init

Open the newly generated tslint.json file and add the no-console rule accordingly:

打开新生成的tslint.json文件,并相应地添加no-console规则:

tslint.json
tslint.json
{  "defaultSeverity": "error",  "extends": ["tslint:recommended"],  "jsRules": {},  "rules": {    "no-console": false  },  "rulesDirectory": []}

By default, the TypeScript linter prevents the use of debugging using console statements, hence the need to explicitly tell the linter to revoke the default no-console rule.

默认情况下,TypeScript linter禁止使用console语句进行调试,因此需要显式告知linter撤消默认的no-console规则。

步骤4 —更新package.json文件 (Step 4 — Updating the package.json File)

At this point in the tutorial, you can either run functions in the terminal individually, or create an to run them.

在本教程的这一点上,您既可以在终端中单独运行函数,也可以创建一个来运行它们。

In this step you will make a start script that will compile and transpile the TypeScript code, and then runs the resulting .js application.

在此步骤中,您将制作一个start脚本,该脚本将编译和转换TypeScript代码,然后运行生成的.js应用程序。

Open the package.json file and update it accordingly:

打开package.json文件并进行相应的更新:

package.json
package.json
{  "name": "node-with-ts",  "version": "1.0.0",  "description": "",  "main": "dist/app.js",  "scripts": {    "start": "tsc && node dist/app.js",    "test": "echo \"Error: no test specified\" && exit 1"  },  "author": "",  "license": "ISC",  "devDependencies": {    "@types/express": "^4.16.1",    "tslint": "^5.12.1",    "typescript": "^3.3.3"  },  "dependencies": {    "express": "^4.16.4"  }}

In the snippet above, you updated the main path and added the start command to the section. When looking at the start command, you’ll see that first the tsc command is run, and then the node command. This will compile and then run the generated output with node.

在上面的代码段中,您更新了main路径,并将start命令添加到了部分。 查看start命令时,您会看到首先运行tsc命令,然后运行node命令。 这将进行编译,然后使用node运行生成的输出。

The tsc command tells TypeScript to compile the application and place the generated .js output in the specified outDir directory as it is set in the tsconfig.json file.

tsc命令告诉TypeScript编译应用程序,并将生成的.js输出放置在tsconfig.json文件中设置的指定outDir目录中。

第5步-创建和运行Basic Express服务器 (Step 5 — Creating and Running a Basic Express Server)

Now that TypeScript and its linter are configured, it is time to build a Node Express Server.

现在已经配置了TypeScript及其linter,现在该构建Node Express服务器了。

First, create a src folder in the root of your project directory:

首先,在您的项目目录的根目录中创建一个src文件夹:

  • mkdir src

    mkdir src

Then create a file named app.ts within it:

然后在其中创建一个名为app.ts的文件:

  • touch src/app.ts

    触摸src / app.ts

At this point, the folder structure should look like this:

此时,文件夹结构应如下所示:

├── node_modules/├── src/  ├── app.ts├── package-lock.json├── package.json├── tsconfig.json├── tslint.json

Open up the app.ts file with a text editor of your choice and paste in the following code snippet:

使用您选择的文本编辑器打开app.ts文件,并粘贴以下代码片段:

src/app.ts
src / app.ts
import express from 'express';const app = express();const port = 3000;app.get('/', (req, res) => {  res.send('The sedulous hyena ate the antelope!');});app.listen(port, err => {  if (err) {    return console.error(err);  }  return console.log(`server is listening on ${port}`);});

The code above creates Node Server that listens on the port 3000 for requests. Run the app using the following command:

上面的代码创建了在端口3000上侦听请求的节点服务器。 使用以下命令运行应用程序:

  • npm start

    npm开始

If it runs successfully, a message will be logged to the terminal:

如果成功运行,将在终端上记录一条消息:

Output
输出量
  • server is listening on 3000

    服务器正在监听3000

Now, you can visit http://localhost:3000 in your browser and you should see the message:

现在,您可以在浏览器中访问http://localhost:3000 ,并且应该看到以下消息:

Output
输出量
  • The sedulous hyena ate the antelope!

    狡猾的鬣狗吃了羚羊!

Open the dist/app.js file and you will find the transpiled version of the TypeScript code:

打开dist/app.js文件,您将找到TypeScript代码的转译版本:

dist/app.js
dist / app.js
"use strict";var __importDefault = (this && this.__importDefault) || function (mod) {    return (mod && mod.__esModule) ? mod : { "default": mod };};Object.defineProperty(exports, "__esModule", { value: true });const express_1 = __importDefault(require("express"));const app = express_1.default();const port = 3000;app.get('/', (req, res) => {    res.send('The sedulous hyena ate the antelope!');});app.listen(port, err => {    if (err) {        return console.error(err);    }    return console.log(`server is listening on ${port}`);});//# sourceMappingURL=app.js.map

At this point you have successfully set up your Node project to use TypeScript.

至此,您已经成功设置了Node项目以使用TypeScript。

结论 (Conclusion)

In this tutorial, you learned about why TypeScript is useful for writing reliable JavaScript code. You also learned about some of benefits to working with TypeScript.

在本教程中,您了解了TypeScript为什么对于编写可靠JavaScript代码有用。 您还了解了使用TypeScript的一些好处。

Finally, you set up a Node project using the Express framework, but compiled and ran the project using TypeScript.

最后,您使用Express框架设置了一个Node项目,但是使用TypeScript编译并运行了该项目。

翻译自:

报纸打字项目

转载地址:http://eohgb.baihongyu.com/

你可能感兴趣的文章
场景3 Data Management
查看>>
Dubbo入门---搭建一个最简单的Demo框架(转)
查看>>
树结构练习——排序二叉树的中序遍历
查看>>
AC自动机模板
查看>>
python 基本语法
查看>>
Oracle JDBC hang on
查看>>
inotify+rsync实现实时热备
查看>>
C#杂问
查看>>
Cocoapods的使用教程
查看>>
Swift - 点击箭头旋转
查看>>
SpringBoot学习(四)
查看>>
深入理解javascript作用域系列第四篇
查看>>
git配置
查看>>
bing智能提示搜索框实现
查看>>
12月月计划与周计划
查看>>
分享Java开发的利器-Lombok
查看>>
实战中总结出来的CSS常见问题及解决办法
查看>>
01-Stanford-Overview of iOS & MVC 摘要及笔记
查看>>
11.5
查看>>
JAVA类加载器一 父类委托机制
查看>>