Typescript를 사용하여 NodeJS-React 프로젝트 설정: 두 서버(Express...

Typescript를 사용하여 NodeJS-React 프로젝트 설정: 두 서버(Express...

반응형

개발 중이지만 변경 사항을 즉시 확인할 수 있는 기능은 프로그래머가 프런트엔드 및 백엔드에 대한 각 코드 라인의 영향을 확인할 수 있는 계획되지 않은 확실성을 쉽게 해 줍니다. NodeJS와 React 서버를 동시에 실행하도록 MERN 프로젝트를 설정하는 방법을 시연하겠습니다. 지금부터 백엔드를 BE, 프런트엔드를 FE, 데이터베이스를 DB라고 하겠습니다. 또한 리눅스 환경에서 작업할 것입니다. 걱정마세요, 리눅스 고유의 명령이 있을 때마다, 제가 지시할께요. 또한 저는 실(Yet Another Resource Negootiator)을 사용할 것입니다. 여러분도 npm(노드 패키지 관리자)을 사용할 수 있습니다. 나는 항상 npm의 유사 콤맨드를 줄 것이다. 시작합시다.

먼저 폴더를 만듭니다. 내 프로젝트를 오스뮴이라고 부르겠습니다.

a) cd를 프로젝트 폴더에 넣고 다음과 같은 두 개의 폴더를 만듭니다.

mkdir {backend,frontend}

b) FE: cd에 필요한 파일을 프런트엔드 디렉터리에 획득합니다. 타이프라이터로 작업할 거예요. 아래 명령을 입력하여 형식 템플릿이 있는 프로젝트 구조를 가져옵니다.

yarn create react-app --template typescript i.e yarn create react-app osmium --template typescript

c) 포장 준비 중.두 서버를 모두 실행하는 json 파일: FE 폴더에서 cd. 다음을 수행할 수 있습니다.

cd ..

이제 두 서버를 모두 실행하는 데 필요한 리소스를 가져오겠습니다.

i) 패키지를 만듭니다.스크립트, 종속성 등을 저장할 json 파일:

yarn init -y or npm init-y

위의 명령을 실행하면 패키지가 즉시 생성됩니다.JSON 파일입니다. tsconfig.json 파일을 추가하려면 다음을 입력합니다.

tsc --init

위의 명령은 tsconfig.json 파일을 생성합니다.

그러나 위의 명령은 타이프스크립트가 설치된 경우에만 사용할 수 있습니다. 그렇지 않으면 다음을 수행합니다.

yarn add -g typescript

d) tsconfig.json 파일 구성:

tsconfig.json 파일에 권장되는 키-값 쌍은 다음과 같이 강조 표시됩니다.

{ "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./backend/dist", /* Redirect output structure to the directory. */ "rootDir": "./backend/src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ /* Module Resolution Options */ "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ "typeRoots": ["./backend/src/types", "../node_modules/@types"], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ "skipLibCheck": true, /* Skip type checking of declaration files. */ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ }, "exclude": ["../node_modules"], "include": ["./backend/src"] }

위의 tsconfig.json 파일에서는 rootDir 및 outDir가 중요합니다. 이들은 소스 코드를 가져올 위치 및 변환된 자바스크립트 파일을 저장할 위치를 각각 알려준다. 따라서 BE 폴더에 src 폴더를 생성했는지 확인합니다. "yarn dev" 명령을 실행하면 "dist" 폴더가 자동으로 생성됩니다.

e) 패키지에서 서버를 실행하는 스크립트 설정.json 파일에서 스크립트 개체를 만들고 다음을 입력합니다.

..... "scripts": { "client": "yarn start --prefix frontend", "server": "nodemon ./backend/dist/index.js", "dev": "rm -rf ./backend/dist/index.js && tsc && concurrently \"yarn server\" \"yarn client\", "start": "node ./backend/dist/index.js" } .....

e) 필요한 devDependencies 라이브러리 추가:

필요한 devDependencies 라이브러리는 다음과 같이 가져올 수 있습니다.

yarn add nodemon concurrently -D // the -D flag implies that the resources are devDependencies

이제 실행할 수 있습니다.

yarn dev

DB 및 기타 리소스를 연결합니다.

읽어주셔서 감사합니다!

from http://issue-disk.tistory.com/39 by ccl(A) rewrite - 2021-10-14 14:25:50