来自github?可以在下面的网站上获得更好的本教程的观看体验:https://pokedpeter.dev
本教程将向您展示如何从头开始构建Barrebons Node(JavaScript)项目,并使用以下好处:
先决条件:
让我们设置一个排骨节点项目
创建我们的节点项目。可以跳过所有提示选项。
mkdir project
cd project
npm init一个名为package.json的文件将设置为您选择的选项。您可以跳过接口选项,并通过运行npm init -y使用默认值
{
"name" : " project " ,
"version" : " 1.0.0 " ,
"description" : " " ,
"main" : " index.js " ,
"scripts" : {
"test" : " echo " Error: no test specified " && exit 1 "
},
"author" : " " ,
"license" : " ISC "
}主要可执行脚本不是自动创建的。创建它。
touch index.js将一些基本的东西放在index.js中以进行测试。
console . log ( 'Hello World' ) ;从CLI进行测试:
node index.js
这为您提供了一些控制台输出:
Hello World
JavaScript不带任何内置标准库。建议的方法是安装NPM软件包。让我们尝试一个例子。我们将安装一个流行的方便实用程序库Lodash。
npm install lodash
这是输出:
added 1 package, and audited 4 packages in 987ms
found 0 vulnerabilities
现在,我们已经插入了Lodash,现在可以在应用程序中使用它。再次打开index.js并更新以匹配:
const _ = require('lodash);
console.log(_.snakeCase('Hello World'));
运行它,您会看到以下输出:
hello_world
再次查看package.json文件,并注意带有lodash条目的新dependencies项部分:
"dependencies" : {
"lodash" : " ^4.17.21 "
}提示
要快速查看CLI中的文件内容,请键入: cat package.json
查看您的项目文件并注意已创建了node_modules文件夹:
$ ls -l
index.js
node_modules
package-lock.json
package.json此文件夹是存储依赖关系的地方。让我们检查一下:
$ ls node_modules
@types lodash typescript让我们将打字稿添加到我们的准则节点项目中。
将打字稿依赖性安装为开发人员。所有打字稿依赖性仅在--save-dev过程中需要
npm install --save-dev typescript安装节点的打字稿类型定义:
npm install --save-dev @types/node提示
将多个软件包安装在一个行中,通过将它们组合在一行中: npm install --save-dev typescript @types/node
看看package.json中的依赖项。这是相关部分:
{
"devDependencies" : {
"@types/node" : " ^20.4.9 " ,
"typescript" : " ^5.1.6 "
}
}通过在项目中的任何位置运行以下命令来初始化打字稿。
npx tsc --init这将创建一个带有默认设置的tsconfig.json文件:
Created a new tsconfig.json with:
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
我们使用npx ,该NPX执行已通过package.json安装的本地安装的二进制文件。
警告
一些安装指南将建议安装打字稿全球sudo npm install -g typescript 。我建议安装本地版本(即在您的项目文件夹中)
全球版本可能最终与为您的项目安装的本地版本有所不同。运行tsc直接使用全局版本。当tsc作为项目中NPM的一部分运行时,它使用本地版本。
默认情况下, tsconfig.json中设置了几个选项。有很多评论的选项 - 未如下显示。
{
"compilerOptions" : {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
"target" : " es5 " , /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module" : " commonjs " , /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
/* Strict Type-Checking Options */
"strict" : true , /* Enable all strict type-checking options. */
/* Module Resolution Options */
"esModuleInterop" : true , /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
/* Advanced Options */
"skipLibCheck" : true , /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames" : true /* Disallow inconsistently-cased references to the same file. */
}
}一些建议对默认值进行调整:
"target" : " es2015 " , // I'd recommend es2015 at a minimum. es5 is ancient.
"outDir" : " build " , // Keep our compiled javascript in the build directory
"rootDir" : " src " , // Keep our source code in a separate directory
"noImplicitAny" : true , // We're using Typescript yeah? And not adding Typescript to an existing project. Enforce good habits from the start.
"lib" : [ " es2020 " ], // Setting this excludes DOM typings as we are using Node. Otherwise you'll run into errors declaring variables like 'name'关于target 。通常,节点的新版本将支持较新的ECMA功能。下面的网站是一个很好的资源,可以查看每个版本的Node都可以使用哪些ECMA功能:
https://node.green/
不再需要索引。
rm index.js设置我们的项目源代码:
mkdir src
cd src
touch index.ts向index.ts添加一些基本的东西以测试它:
console . log ( 'Hello typescript!' ) ;编译我们的Barrebones项目。
npx tsc如JavaScript,可以在/build Directory中找到编译的输出。它将包含index.js镜像我们的src/index.ts
index.js的内容:
"use strict" ;
console . log ( 'Hello World!' ) ;您现在准备使用Typescript构建JavaScript项目!
直到最近,TSLINT还是TOXECTICT代码Linter,但由于该项目已合并到ESLINT中,因此已对其进行弃用。这是官方主页:
网站:
https://eslint.org
GitHub网站:
https://github.com/typescript-eslint/typescript-eslint
安装ESLINT(当然是DEV依赖性)
npm install --save-dev eslint让我们使用ESLINT的INIT命令来设置我们的棉绒配置:
npx eslint --init按照提示。我们正在使用节点,因此不需要浏览器支持。它会问您是否要安装因打字稿插件。继续前进。
✔ How would you like to use ESLint ? · problems
✔ What type of modules does your project use ? · esm
✔ Which framework does your project use ? · none
✔ Does your project use TypeScript ? · No / Yes
✔ Where does your code run ? · node
✔ What format do you want your config file to be in ? · JSON
The config that you ' ve selected requires the following dependencies:
@typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
✔ Would you like to install them now with npm? · No / Yes
Successfully created .eslintrc.json file in /your/project有关绒毛配置的更多信息:
https://eslint.org/docs/user-guide/configuring
使用上面选择的选项,我们的.eslintrc.json文件看起来像这样:
{
"env" : {
"es2020" : true ,
"node" : true
},
"extends" : [
" eslint:recommended " ,
" plugin:@typescript-eslint/recommended "
],
"parser" : " @typescript-eslint/parser " ,
"parserOptions" : {
"ecmaVersion" : 11 ,
"sourceType" : " module "
},
"plugins" : [
" @typescript-eslint "
],
"rules" : {
}
}您可能已经注意到Eslint Init过程中的一个问题之一是:
? How would you like to use ESLint ? …
To check syntax only
▸ To check syntax and find problems
To check syntax, find problems, and enforce code style最后一个选项还可以执行代码样式。如果您选择该选项,那么后续问题将是:
? How would you like to define a style for your project ? …
▸ Use a popular style guide
Answer questions about your style
Inspect your JavaScript file(s)如果您选择使用流行样式指南,那么您将从以下选择中进行选择:
? Which style guide do you want to follow ? …
▸ Airbnb: https://github.com/airbnb/javascript
Standard: https://github.com/standard/standard
Google: https://github.com/google/eslint-config-google
XO: https://github.com/xojs/eslint-config-xo我建议研究上述样式指南,并与您的喜好相符的指南。
接下来,我们将在原始文本中创建另一个配置文件,以允许我们从覆盖中排除文件和目录:
touch .eslintignore并将以下内容添加到文件:
node_modules
build
我们不想在编译的JavaScript代码上覆盖。
默认情况下,启用了标准规则。请参阅列表中的滴答物品:
https://eslint.org/docs/rules/
例如,让我们尝试打破no-extra-semi规则。
尝试在index.ts中将半彩色添加到行的末端,然后进行皮棉检查以查看错误:
console . log ( 'Hello typescript' ) ; ;进而:
npx eslint src这导致:
1:34 error Unnecessary semicolon @typescript-eslint/no-extra-semi
✖ 1 problem (1 error, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
警告
安装Airbnb选项时,我注意到Eslint需要传递.TS文件扩展名:
npx eslint src --ext .ts在package.json中为此创建一个脚本。JSON,因此我们可以方便地称呼它:
"scripts" : {
...
"lint" : " eslint src --ext .ts "
},仅在NPM <V7上使用时适用,但请注意,如果您运行NPM脚本并找到问题,您将看到以下NPM错误消息附加在ESLINT输出下方:
> eslint src --ext .ts
/home/user/dev/test/src/index.ts
1:1 warning Unexpected console statement no-console
1:21 error Missing whitespace after semicolon semi-spacing
1:22 error Unnecessary semicolon no-extra-semi
✖ 3 problems (2 errors, 1 warning)
2 errors and 0 warnings potentially fixable with the ` --fix ` option.
npm ERR ! code ELIFECYCLE
npm ERR ! errno 1
npm ERR ! [email protected] lint: ` eslint src --ext .ts `
npm ERR ! Exit status 1
npm ERR !
npm ERR ! Failed at the [email protected] lint script.
npm ERR ! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR ! A complete log of this run can be found in:
npm ERR ! /home/user/.npm/_logs/2021-08-18T15_27_55_318Z-debug.log在NPM V7上,我看不到NPM错误(例如,使用节点16.6.2)
每个规则可以是三个州之一:
| 规则模式 | 描述 |
|---|---|
| 0或“关” | 禁用规则 |
| 1或“警告” | 警告,Linter不会失败 |
| 2或“错误” | 错误,衬里将失败 |
可以将规则添加为Lint Config File .eslintrc.json中的规则对象的键:
{
"root" : true ,
"parser" : " @typescript-eslint/parser " ,
"plugins" : [ ... ],
"extends" : [ ... ],
"rules" : {
..your rules go here..
}
}在eslint.org上查找规则:
https://eslint.org/docs/rules/
让我们测试名为“ Comma-Dangle”的风格规则。如果有多行的数组在最后一项上缺少逗号,我们想警告用户。
添加规则:
"rules" : {
"comma-dangle" : [
" warn " , {
"arrays" : " always-multiline "
}
]
}阅读网站上的规则详细信息。许多规则都可以自定义。在此示例中,我们想在所有情况下都覆盖悬空逗号。
使用以下代码更改index.ts:
const movies = [
'Lord of the Flies' ,
'Battle Royale'
] ;
movies . pop ( ) ;运行Linter:
npx eslint src现在,我们应该看到以下警告:
3:18 warning Missing trailing comma comma-dangle
✖ 1 problem (0 errors, 1 warning)
0 errors and 1 warning potentially fixable with the ` --fix ` option.注意输出中有一个解决问题的选项。尝试使用--fix选项运行Linter:
npx eslint --fix src这次没有衬里的输出,如果我们检查index.ts 。
const movies = [
'Lord of the Flies' ,
'Battle Royale' , // <-- dangling comma added
] ;
movies . pop ( ) ; 我们将使用更漂亮的格式代码。这是一种自以为是的代码格式化器,支持许多语言,包括打字稿,JavaScript和其他您可能用于JSON和YAML等配置的格式。
https://prettier.io
另外,您可以坚持使用ESLINT,以形式上格式化代码。漂亮的不同之处在于,除非您设置少数选项之一,否则它不会修改您的代码。
安装模块:
npm install --save-dev prettier创建配置文件。这使编辑器和其他工具知道您使用的是更漂亮:
echo {} > .prettierrc.json您可能不需要在配置文件中添加任何选项,因为大多数将涉及转换代码。最好将其留给Eslint,然后让更漂亮的处理格式。
创建一个忽略文件。这使得更漂亮的CLI和编辑知道哪些文件将排除在格式化之外。
touch .prettierignore将以下行添加到.prettierignore :
node_modules
build通过以下命令测试Prettier。它不会占用任何内容,只是输出格式的代码:
npx prettier src根据我们对索引的最后更改,输出将为:
const movies = [ "Lord of the Flies" , "Battle Royale" ] ;
movies . pop ( ) ;我们可以看到,多行阵列已格式化为一行。
通过使用选项重复该命令来写更改文件: --write :
npx prettier --write src这将列出已格式的文件:
src/index.ts 279ms鉴于Eslint和Prettier可以格式化代码,您可以预期会发生一些冲突。 Prettier专门为ESLINT创建了规则,该规则基本上会禁用与更漂亮的任何不必要或冲突的规则。
第一个是eslint-config-prettier :
https://github.com/prettier/eslint-config-prettier
该配置关闭所有不必要或与更漂亮的规则。使用以下命令安装它:
npm install --save-dev eslint-config-prettier然后,将其添加到Eslint Config的extends部分的最后一行中, .eslintrc.json :
{
"extends" : [
"eslint:recommended" ,
"plugin:@typescript-eslint/recommended" ,
"plugin:@typescript-eslint/eslint-recommended" ,
"prettier" // <-- Add this
] ,
}您可以在任何文件上运行以下命令,以检查Eslint和Prettier之间没有冲突:
npx eslint-config-prettier src/index.ts如果一切顺利,您应该得到以下呼吸:
No rules that are unnecessary or conflict with Prettier were found.下一个要安装的是eslint-plugin-prettier :
https://github.com/prettier/eslint-plugin-prettier
作为ESLINT规则,运行更漂亮,并将差异作为单个ESLINT问题报告。使用以下命令安装它:
npm install --save-dev eslint-plugin-prettier然后更新您的.eslintrc.json文件如下:
{
"plugins" : [ " prettier " ],
"rules" : {
"prettier/prettier" : " error "
}
}搜索以下插件:
ESLint由Dirk Baeumer撰写
搜索以下插件:
Prettier - Code formatter - 由
按Ctrl + Shift + I格式代码。提示您选择默认格式。选择“默认值更漂亮”。
搜索以下插件:
Prettier ESLint丽贝卡背心
这些脚本是针对我们的打字稿项目量身定制的。我们只检查.ts文件。
将以下命令添加到package.json的scripts部分。
"start:dev" : " nodemon " "lint" : " eslint --ext .ts src "
"lint-fix" : " eslint --fix --ext .ts src " "pretty" : " prettier --write 'src/**/*.ts' " 曲线球是在节点中构建API的微型框架。它是从头到尾构建的,支持打字稿,而不是其更受欢迎的前身KOA。
https://curveballjs.org/
安装它:
npm install @curveball/core将网站示例复制到index.ts 。我们将更改的唯一一件事是端口号。有两个原因。一个,端口80可能会被阻塞。二。在不同端口上运行,使我们可以同时运行多个节点项目。
import { Application } from '@curveball/core' ;
const app = new Application ( ) ;
app . use ( async ctx => {
ctx . response . type = 'text/plain' ;
ctx . response . body = 'hello world' ;
} ) ;
app . listen ( 9000 ) ;使用我们之前创建的脚本以DEV模式启动服务器:
npm run start:dev随着Nodemon聆听文件更改,您将获得以下输出:
> [email protected] start:dev /home/your_name/project
> nodemon
[nodemon] 2.0.4
[nodemon] to restart at any time, enter ` rs `
[nodemon] watching path(s): src/ ** / *
[nodemon] watching extensions: ts,js更改代码后,请注意服务器控制台输出在工作中为Nodemon。还要刷新网页以查看更新。
在更改代码以进行开发之后,设置自动重新加载。安装nodemon以监视文件更改和ts-node以直接运行打字稿代码,而不必编译然后传递到node 。
npm install --save-dev ts-node nodemon添加nodemon.json配置。这将配置Nodemon,以关注源代码目录中的.TS和.JS文件的更改,然后在更改后运行EXEC命令。
{
"watch" : [ " src " ],
"ext" : " .ts,.js " ,
"ignore" : [],
"exec" : " ts-node ./src/index.ts "
}在package.json中添加一个NPM脚本。JSON以启动nodemon进行开发:
"start:dev" : " nodemon "运行npm run start:dev即可开始重新加载过程。
安装Docker和查找说明有关如何在没有SUDO的情况下运行Docker的说明 - 此处省略了OS / DISTRO特定的说明。
用单个节点容器作为服务创建一个docker-compose.yml文件:
我们项目的名称是“项目”,服务和容器的名称也是如此。我们有一个卷将项目目录映射到节点容器内的 /项目。最后,确保端口与应用程序中暴露的端口匹配。
以下更多详细信息:
https://docs.docker.com/compose/compose-file/
version : ' 3 '
services :
project :
build : .
container_name : project
volumes :
- .:/project
ports :
- " 9000 "接下来,使用以下内容创建Dockerfile 。
FROM node:12
WORKDIR /project
COPY package.json .
RUN npm install
COPY . .
CMD [ "npm" , "run" , "start:dev" ]这可以在容器内设置我们的项目目录,安装我们的节点软件包,对本机文件系统的内容复制,并在DEV模式下启动我们的CurveBall Server。
现在提出容器:
docker-compose up您会看到以下输出:
Creating network "project_default" with the default driver
Building project
Step 1/7 : FROM node:12
---> dfbb88cfffc8
Step 2/7 : WORKDIR /project
---> Running in 86fff3a3c90b
Removing intermediate container 86fff3a3c90b
---> 5912fd119492
Step 3/7 : COPY package.json .
---> 4fa4df04cc6b
Step 4/7 : RUN npm install
---> Running in 8b814e4d75d2
...
(Node package installation happens here)
...
Removing intermediate container 8b814e4d75d2
---> 3bfd2b1a83e4
Step 5/7 : COPY . .
---> f6971fdf7fb5
Step 6/7 : EXPOSE 9000
---> Running in 2ab0a152b0a6
Removing intermediate container 2ab0a152b0a6
---> 0e883b79c1b3
Step 7/7 : CMD ["npm", "run", "start:dev"]
---> Running in f64884ae2643
Removing intermediate container f64884ae2643
---> 1abb8edf6373
Successfully built 1abb8edf6373
Successfully tagged project_project:latest
WARNING: Image for service project was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating project ...
Creating project ... done
Attaching to project
project |
project | > [email protected] start:dev /project
project | > nodemon
project |
project | [nodemon] 2.0.4
project | [nodemon] to restart at any time, enter `rs`
project | [nodemon] watching path(s): src/**/*
project | [nodemon] watching extensions: ts,js
project | [nodemon] starting `ts-node ./src/index.ts`
您可以使用CTRL-C停止容器。
使用docker-compose up -d以独立模式将容器提起 - 它在括号中提出,您可以自由地继续使用命令行。
我们正在基于节点V12创建一个容器。我们的工作目录将容器内的工作目录定义为/project (我们的项目代码将在其中映射到)
安装的节点的版本将取决于已安装的操作系统以及其包装的最新情况。
如果您在Docker容器外使用节点并在多个节点项目上工作,每个节点项目需要不同版本的节点,则安装NVM:
https://github.com/nvm-sh/nvm
非常感谢以下帮助我创建本教程。