报纸打字项目_使用打字稿设置节点项目

报纸打字项目

Node, a run-time environment that makes it possible to write server-side JavaScript, has gained a lot of adoption since its release in 2011. Writing server-side JavaScript is incredible but can get messy as the codebase grows, owing to the nature of the JavaScript language; dynamic and weak typed.

Node是一个运行时环境,可以编写服务器端JavaScript,自2011年发布以来已获得广泛采用。编写服务器端JavaScript令人难以置信,但由于代码的自然特性,它会变得混乱JavaScript语言; 动态型弱型型

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

来自其他语言JavaScript开发人员经常抱怨它缺乏强静态类型 ; 这就是TypeScript进入图片的地方,以弥合这种差距。

TypeScript is a typed (optional) super-set of JavaScript that can make it easier to build and manage large-scale JavaScript projects. It can be thought of as JavaScript with additional features such as strong static typing, compilation and object oriented programming etc.

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

Note: TypeScript being a super-set of JavaScript 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.

    使用界面的能力。

This tutorial will primarily teach you to set up a Node project with TypeScript. We will build a simple Express application using TypeScript and transpile it down to neat, reliable JavaScript code.

本教程将主要教您使用TypeScript设置Node项目。 我们将使用TypeScript构建一个简单的Express应用程序,并将其转换为整洁,可靠JavaScript代码。

Let’s begin!

让我们开始!

先决条件 ( Prerequisites )

  1. This tutorial assumes a basic knowledge of Node

    本教程假定您具有Node的基本知识

配置 ( Setting up )

In this section, we will go over the setup and configuration required to enable our computer to run a simple Node application using TypeScript.

在本节中,我们将介绍使计算机能够使用TypeScript运行简单的Node应用程序所需的设置和配置。

安装节点 (Installing Node)

This step is only necessary if you do not already have Node installed on your machine. If you do feel free to skip.

仅当您尚未在计算机上安装Node时,才需要执行此步骤。 如果您愿意,请跳过。

Let’s begin by installing the Node run-time on our machine. If you are on a Debian or Ubuntu distro of Linux, fire up a new instance of the terminal and run the following commands:

让我们从在计算机上安装Node运行时开始。 如果您使用的是Linux的Debian或Ubuntu版本,请启动终端的新实例并运行以下命令:

$curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
$ sudo apt-get install -y nodejs

You will need curl installed on your machine to run the first command. Curl is a command-line tool for transferring data using various protocols.

您将需要在计算机上安装curl以运行第一个命令。 Curl是用于使用各种协议传输数据的命令行工具。

If you are on a different operating system, head over here for Node installation instructions.

如果您使用的是其他操作系统,请访问此处获取Node安装说明。

Once the installation is complete, we can confirm that it was successful by checking the Node and Npm versions installed:

安装完成后,我们可以通过检查Node和 Npm 安装的版本:

$ node -v
$npm -v

At the time of writing this article, the stable versions for Node and Npm are 10.15.1 and 6.7.0 respectively.

在撰写本文时,Node和10.15.1的稳定版本分别为10.15.16.7.0

初始化一个Npm项目 (Initializing an Npm project)

Now that we have Node and Npm installed, we will create a new folder for our project and initialize it as an Npm project:

现在我们已经安装了Node和Npm,我们将为我们的项目创建一个新文件夹并将其初始化为Npm项目:

$mkdir node_project
$ cd node_project
$ npm init

Note: After running npm init, you will need to supply Npm with information about your project. However, if you'd rather let Npm guess sensible defaults then you can add the y flag: npm init -y

注意:在运行npm init之后,您将需要向Npm提供有关您的项目的信息。 但是,如果您希望让Npm猜测合理的默认值,则可以添加y标志:npm init -y

安装依赖项 (Installing Dependencies)

We have successfully initialized a bare Npm project but haven’t installed the dependencies required to runTypescript. Navigate into the project directory we just created and run the following commands on the terminal:

我们已经成功地初始化了一个简单的Npm项目,但尚未安装运行Typescript所需的依赖 。 导航到我们刚刚创建的项目目录,并在终端上运行以下命令:

$npm install -D typescript
$ npm install -D tslint

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

-D标志是--save-dev的快捷方式。 您可以在此处了解更多信息

Wonderful, now we need to install the Express framework:

太棒了,现在我们需要安装Express框架:

$npm install express -S
$ npm install @types/express -D

The second command above installs the Express types. We need this package because TypeScript and Express are independent packages hence there is no way for TypeScript to know about the types of Express classes.

上面的第二个命令将安装Express类型。 我们需要此软件包,因为TypeScript和Express是独立的软件包,因此TypeScript无法了解Express类的类型。

Types in TypeScript are files, normally with an extension of .d.ts*, used to provide type information about an API, in our case Express.

TypeScript中的类型是文件,通常以.d.ts *扩展名,用于提供有关API(在我们的情况下为Express)的类型信息。

配置TypeScript (Configuring TypeScript)

In this section, we will setup TypeScript and configure linting for TypeScript. TypeScript uses the tsconfig.json file 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文件,并粘贴以下代码段:

{
  "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 and see what they do:

让我们看一下上面的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 Valuenode mimics the Node module resolution mechanism.

    moduleResolution :这可以帮助编译器弄清楚导入是指什么。 值node模仿节点模块解析机制。
  • outDir: This is the location to output .js files after transpilation. We save it as dist.

    outDir :这是在编译后输出.js文件的位置。 我们将其另存为dist

ProTip: An alternative to manually creating and populating the tsconfig.json file is running: tsc --init. This command will generate a nicely commented tsconfig.json file. To learn more about the key value options available, check out the official TypeScript documentation.

ProTip:正在运行手动创建和填充tsconfig.json文件的替代方法:tsc --init。 此命令将生成一个注释良好的tsconfig.json文件。 要了解更多有关可用的键值选项,检查出的正式打字文档 umentation

Let’s now configure TypeScript linting for the project. In a terminal that is pointed to the root of our project’s directory, run the following command to generate a tslint.json file:

现在,为项目配置TypeScript棉绒。 在指向项目目录根目录的终端中,运行以下命令以生成tslint.json文件:

$ ./node_modules/.bin/tslint --init

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

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

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

By default, the Typescript linter prevents the use of our favorite debugger, console, hence the need to explicitly tell the linter to revoke its default no-console rule.

默认情况下,Typescript linter阻止使用我们最喜欢的调试器console ,因此需要明确告诉linter撤销其默认的no-console规则。

更新Package.json文件 (Updating the Package.json file)

At this point in the tutorial, we can either directly run functions in the terminal or create an 'npm script' to neatly run them for us. Let’s go with the latter, we will make a “start” script that compiles and transpiles the TypeScript code, then runs the resulting .js application.

在本教程的这一点上,我们可以直接在终端中运行函数,也可以创建“ npm script ”来为我们巧妙地运行它们。 让我们来看一下后者,我们将创建一个“开始”脚本,该脚本可以编译和转译TypeScript代码,然后运行生成的.js应用程序。

Open the package.json file and update it accordingly:

打开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, we updated the main path and added the start command to the 'npm scripts.' Taking a close look at the start command, we are first running the tsc command and then the node command. This will enable us to compile and run the generated output with node.

在上面的代码段中,我们更新了main路径,并将start命令添加到了' npm scripts '。 仔细看一下start命令,我们首先运行tsc命令,然后运行node命令。 这将使我们能够使用node编译并运行生成的输出。

NOTE: 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目录中。

设置文件夹结构 ( Setting Up The Folder Structure )

We will create a src folder in the root of our project directory and then create a file called app.ts within it:

我们将在项目目录的根目录中创建一个src文件夹,然后在其中创建一个名为app.ts的文件:

$mkdir src
$ cd src
$ touch app.ts

At this point, we should have a folder structure that looks like this:

此时,我们应该具有如下所示的文件夹结构:

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

创建和运行基本Express服务器 ( Creating and Running a Basic Express Server )

Now that we’ve configured TypeScript and its linter, we will build a basic Node Express Server. Open up the app.ts file and paste in the following code snippet:

现在,我们已经配置了TypeScript及其Linter,我们将构建一个基本的Node Express Server。 打开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 describes a basic Node Server which simply listens on the port 3000 for requests. Let’s run the app using the following command:

上面的代码描述了一个基本的节点服务器,它仅在端口3000上侦听请求。 让我们使用以下命令运行该应用程序:

$npm start

If it runs successfully, we get a message logged to the terminal “server is listening on 3000.” Now we can visit_ _http://localhost:3000 on the browser and we will see this message “The sedulous hyena ate the antelope!

如果成功运行,我们会收到一条消息记录到终端“服务器正在监听3000”。 现在,我们可以在浏览器上访问 _ _http:// localhost:3000 ,我们将看到以下消息: “贪婪的鬣狗吃了羚羊

We can now open the dist/app.js file and we will find the transpiled version of the TypeScript code:

现在我们可以打开dist/app.js文件,我们将找到TypeScript代码的转译版本:

"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

Awesome, you have successsfully set up your Node project to use TypeScript!

太棒了,您已经成功设置了Node项目以使用TypeScript!

结论 ( Conclusion )

In this tutorial, we went over a few reasons that make TypeScript important to writing reliable JavaScript code. We also looked at some benefits of working with TypeScript.

在本教程中,我们介绍了一些使TypeScript对编写可靠JavaScript代码很重要的原因。 我们还研究了使用TypeScript的一些好处。

Finally, we followed simple steps and learnt how to set up a Node project with TypeScript.

最后,我们遵循简单的步骤,并学习了如何使用TypeScript设置Node项目。

翻译自: https://scotch.io/tutorials/setting-up-a-node-project-with-typescript

报纸打字项目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值