來自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
非常感謝以下幫助我創建本教程。