本文共 10813 字,大约阅读时间需要 36 分钟。
报纸打字项目
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的一些好处:
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代码。
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。 您可以按照操作系统的“ 指南来完成此操作。
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项目:
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
标志以跳过提示以获取其他信息:
Now that your project space is set up, you are ready to move on to install the necessary 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:
从项目目录运行以下命令以安装依赖项:
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:
现在,该安装框架了:
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类的类型。
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
文件,并粘贴以下代码段:
{ "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
文件的另一种方法是运行以下命令:
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
文件:
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 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
规则。
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
文件并进行相应的更新:
{ "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
目录中。
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
文件夹:
Then create a file named app.ts
within it:
然后在其中创建一个名为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
文件,并粘贴以下代码片段:
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
上侦听请求的节点服务器。 使用以下命令运行应用程序:
If it runs successfully, a message will be logged to the terminal:
如果成功运行,将在终端上记录一条消息:
Now, you can visit http://localhost:3000
in your browser and you should see the message:
现在,您可以在浏览器中访问http://localhost:3000
,并且应该看到以下消息:
Open the dist/app.js
file and you 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
At this point you have successfully set up your Node project to use TypeScript.
至此,您已经成功设置了Node项目以使用TypeScript。
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/