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

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

报纸打字项目

Node, a 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; and .

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

Developers coming to JavaScript from other languages often complain about its lack of ; 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 application using TypeScript and transpile it down to neat, reliable JavaScript code.

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

Let’s begin!

让我们开始!

( )

  1. This tutorial assumes a basic knowledge of Node

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

( )

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 installed on your machine to run the first command. Curl is a command-line tool for transferring data using various protocols.

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

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

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

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

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

$ 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 run. Navigate into the project directory we just created and run the following commands on the terminal:

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

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

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

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

Wonderful, now we need to install the framework:

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

$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

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

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 '' 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.

在本教程的这一点上,我们可以直接在终端中运行函数,也可以创建“ ”来为我们巧妙地运行它们。 让我们来看一下后者,我们将创建一个“开始”脚本,该脚本可以编译和转译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 '.' 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命令添加到了' '。 仔细看一下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目录中。

( )

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

( )

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 on the browser and we will see this message “The sedulous hyena ate the antelope!

如果成功运行,我们会收到一条消息记录到终端“服务器正在监听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!

( )

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项目。

翻译自:

报纸打字项目

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

你可能感兴趣的文章
Array.of使用实例
查看>>
【Luogu】P2498拯救小云公主(spfa)
查看>>
如何获取网站icon
查看>>
几种排序写法
查看>>
java 多线程的应用场景
查看>>
dell support
查看>>
转:Maven项目编译后classes文件中没有dao的xml文件以及没有resources中的配置文件的问题解决...
查看>>
解决“Eclipse中启动Tomcat后,http://localhost:8080/无法访问”的问题
查看>>
LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
查看>>
百度杯WriteUp
查看>>
test
查看>>
系统日志2-日志查询
查看>>
作用域和 DOM
查看>>
P1280 尼克的任务
查看>>
jemter --分布式部署测试
查看>>
CSS属性选择符
查看>>
Open Source Streaming Server--EasyDarwin
查看>>
【面试题】比给定数大的最小数
查看>>
什么是PHP无限级分类
查看>>
Git的使用--如何将本地项目上传到Github
查看>>