Github에서오고 있습니까? 이 튜토리얼의 더 나은 시청 경험은 아래 사이트에서 https://pokedpeter.dev를 사용할 수 있습니다.
이 튜토리얼은 다음과 같은 장점으로 Barebones 노드 (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 typescriptBarebones 노드 프로젝트에 TypeScript를 추가 할 수 있습니다.
Typecript Dependency를 DEV DEPEDENCY로 설치하십시오. 모든 타입 스크립트 종속성은 개발 중에 만 필요하므로 --save-dev
npm install --save-dev typescript노드의 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 "
}
}프로젝트 내 어디서나 다음 명령을 실행하여 TypeScript를 초기화합니다.
npx tsc --init 이렇게하면 기본 설정이있는 tsconfig.json 파일이 생성됩니다.
Created a new tsconfig.json with:
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
우리는 package.json 통해 설치된 로컬로 설치된 바이너리를 실행하는 npx 사용합니다.
경고
일부 설치 가이드는 전 세계적으로 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 기능을 지원합니다. 아래 웹 사이트는 각 버전의 노드에서 사용할 수있는 ECMA 기능을 볼 수있는 훌륭한 리소스입니다.
https://node.green/
더 이상 index.js가 필요하지 않습니다 :
rm index.js프로젝트 소스 코드 설정 :
mkdir src
cd src
touch index.ts index.ts 에 기본을 추가하여 테스트하십시오.
console . log ( 'Hello typescript!' ) ;베어 본 프로젝트를 컴파일하십시오.
npx tsc JavaScript와 같이 컴파일 된 출력은 /build 디렉토리에서 찾을 수 있습니다. src/index.ts 미러링하는 index.js 포함됩니다
index.js의 내용 :
"use strict" ;
console . log ( 'Hello World!' ) ;이제 TypeScript로 JavaScript 프로젝트를 구축 할 준비가되었습니다!
최근까지 TSLINT는 To-To Typectript Code Linter 였지만 프로젝트가 Eslint로 통합되어 이제는 더 이상 사용되지 않았습니다. 공식 홈페이지는 다음과 같습니다.
웹 사이트 :
https://eslint.org
Github 사이트 :
https://github.com/typescript-eslint/typescript-eslint
eslint 설치 (물론 개발자의 종속성)
npm install --save-dev eslinteslint의 init 명령을 사용하여 보강 구성을 설정하겠습니다.
npx eslint --init프롬프트를 따르십시오. 우리는 노드를 사용하고 있으므로 브라우저 지원이 필요하지 않습니다. 종속식 TypeScript 플러그인을 설치할 것인지 묻습니다. 계속해서 그렇게하십시오.
✔ 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/projectLint 구성에 대한 자세한 내용은 다음과 같습니다.
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위의 스타일 가이드를 조사하고 선호도에 맞는 가이드를 사용하는 것이 좋습니다.
다음으로 Plaint Text로 다른 구성 파일을 만들어서 파일과 디렉토리를 Linting에서 제외 할 수 있습니다.
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.
경고
에어 비앤비 옵션을 설치할 때 eslint가 .ts 파일 확장자가 통과해야한다는 것을 알았습니다.
npx eslint src --ext .ts package.json 에서이 스크립트를 작성하여 편리하게 호출 할 수 있습니다.
"scripts" : {
...
"lint" : " eslint src --ext .ts "
},NPM <V7에서만 적용 가능하지만 NPM 스크립트를 실행하고 문제가 발견되면 ESLINT 출력 아래에 다음 NPM 오류 메시지가 표시됩니다.
> 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.logNPM V7에서 NPM 오류가 표시되지 않습니다 (예 : 노드 16.6.2를 사용할 때)
각 규칙은 세 가지 상태 중 하나 일 수 있습니다.
| 규칙 모드 | 설명 |
|---|---|
| 0 또는 "Off" | 규칙을 비활성화합니다 |
| 1 또는 "경고" | 경고, Linter는 실패하지 않습니다 |
| 2 또는 "오류" | 오류, Linter가 실패합니다 |
RINT CONFIG 파일에서 규칙 객체의 키로 규칙을 추가 할 수 있습니다 .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 이번에는 Linter의 출력이 없으며 index.ts 확인하면 Dangling Comma가 자동으로 추가되었음을 알 수 있습니다.
const movies = [
'Lord of the Flies' ,
'Battle Royale' , // <-- dangling comma added
] ;
movies . pop ( ) ; 더 예쁘게 사용하여 코드를 포맷하겠습니다. TypeScript, JavaScript 및 JSON 및 YAML과 같은 구성에 사용할 수있는 기타 형식을 포함한 많은 언어를 지원하는 의견이 많은 Code Formatter입니다.
https://prettier.io
또는 ESLINT를 사용하여 코드를 스타일로 만들 수 있습니다. 더 작은 옵션 중 하나를 설정하지 않으면 더 예쁘게 코드를 수정하지 않는다는 점이 다릅니다.
모듈 설치 :
npm install --save-dev prettier구성 파일을 만듭니다. 이를 통해 편집자 및 기타 도구는 더 예쁘게 사용하고 있음을 알 수 있습니다.
echo {} > .prettierrc.json대부분이 코드 변환과 관련되므로 구성 파일에 옵션을 추가 할 필요가 없습니다. 가장 좋은 것은 Eslint에게 남겨두고 더 예쁘게 서식을 다루게하십시오.
무시 파일을 만듭니다. 이를 통해 Pretier CLI 및 편집자는 서식에서 제외 할 파일을 알 수 있습니다.
touch .prettierignore .prettierignore 에 다음 줄을 추가하십시오.
node_modules
build다음 명령으로 더 예쁘게 테스트하십시오. 형식화 된 코드를 출력하는 것만으로도 과도하지 않습니다.
npx prettier srcINdex.ts 로의 마지막 변경에 따라 출력은 다음과 같습니다.
const movies = [ "Lord of the Flies" , "Battle Royale" ] ;
movies . pop ( ) ;멀티 라인 어레이가 단일 라인으로 형식화되었음을 알 수 있습니다.
--write 을 사용하여 명령을 반복하여 파일에 변경 사항을 작성하십시오.
npx prettier --write src포맷 된 파일이 나열됩니다.
src/index.ts 279msEslint와 Pretier가 코드를 포맷 할 수있는 경우 일부 충돌이 발생할 것으로 예상 할 수 있습니다. 더 Pretier는 Eslint에 대한 규칙을 작성하여 기본적으로 더 Pretier와 결합 할 때 불필요하거나 상충되는 규칙을 비활성화했습니다.
첫 번째는 eslint-config-prettier 입니다.
https://github.com/prettier/eslint-config-prettier
이 구성은 불필요하거나 더 예쁘게 충돌하는 모든 규칙을 끕니다. 다음 명령으로 설치하십시오.
npm install --save-dev eslint-config-prettier 그런 다음 eslint config, .eslintrc.json 의 extends 섹션의 마지막 줄에 추가하십시오.
{
"extends" : [
"eslint:recommended" ,
"plugin:@typescript-eslint/recommended" ,
"plugin:@typescript-eslint/eslint-recommended" ,
"prettier" // <-- Add this
] ,
}모든 파일에서 다음 명령을 실행하여 Eslint와 Pretier 사이에 충돌이 없는지 확인할 수 있습니다.
npx eslint-config-prettier src/index.ts모든 것이 잘되면 다음과 같은 respone을 받아야합니다.
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 눌러 코드를 포맷하십시오. 기본 포맷터를 선택하라는 메시지가 표시됩니다. 기본값으로 Pretier를 선택하십시오.
아래 플러그인 검색 :
Prettier ESLint Rebecca Vest에 의해
이 스크립트는 우리의 TypeScript 프로젝트에 맞게 조정됩니다. .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와는 달리 TypeScript를 지원하여 처음부터 구축되었습니다.
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:devNodemon이 파일 변경을 듣기 때문에 다음과 같은 출력을 얻게됩니다.
> [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 모니터링하여 컴파일하지 않고 직접 TypeScript 코드를 실행 한 다음 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 스크립트를 추가하여 개발을 위해 nodemon 시작하십시오.
"start:dev" : " nodemon " 실행 npm run start:dev 다시로드 프로세스를 시작하십시오.
Sudo없이 Docker를 실행하는 방법에 대한 Docker 및 조회 지침을 설치하십시오. OS / 배포판 특정이므로 여기에서 생략되었습니다.
서비스로 단일 노드 컨테이너가있는 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 모드에서 커브 볼 서버를 시작합니다.
이제 컨테이너를 가져옵니다.
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 로 정의됩니다 (프로젝트 코드가 매핑 될 때)
설치된 노드의 버전은 설치된 OS 및 최신 패키지의 방법에 따라 다릅니다.
Docker 컨테이너 외부의 노드를 사용하고 여러 노드 프로젝트에서 다른 버전의 노드가 필요한 경우 NVM을 설치하는 경우 :
https://github.com/nvm-sh/nvm
이 튜토리얼을 만드는 데 도움을 준 다음 덕분에 큰 감사를드립니다.