프로젝트 시작하기

nest 프로젝트 만들기

  • nestjs/cli를 깐다. (당연 node는 설치되어 있어야..) 경로는 나는.. dev 폴더 …ㅋㅋ
  • npm install -g @nestjs/cli@latest
  • nest 프로젝트를 만들자 → 경로가 생성된다! dev 폴더 아래에
  • nest new daracbang
  • 아래와 같은 파일들이 만들어진다.
  • 01_001_nest생성, 01_001_nest생성로그
  • pakage.json 에 가면 npm 과 node를 실행하는 script 들이 있는데 start:dev를 하면 nest 앱이 시작된다.
  • 01_001_nest앱실행
  • 기본 포트가 3000번으로 되어 있으므로(src/main.ts) http:localhost:3000으로 접속하면 접속이 된다.
  • 01_001_3000번포트로

nestjs 패키지 깔기

  • @nestjs/common, @nestjs/core, @nestjs/platform-express, @nestjs/serve-static 설치 해야 함
  • 모든 패키지가 버전이 다르면 conflic가 오므로 버전을 최신으로 맞춰 주고자 함
  • npm install @nestjs/cli@latest @nestjs/common@latest @nestjs/core@latest @nestjs/platform-express@latest @nestjs/serve-static@latest

nextjs 패키지 깔기

  • next, react, react-dom 깔기
  • npm install next react react-dom
  • 개발을 위해 @types/react @types/node 깔기
  • npm install --save-dev @types/react @types/node

next 프로젝트 만들기

  • 프로젝트의 루트 경로에 pages라는 폴더를 만든다
    • next가 이 폴더를 root 로 생각하므로 없으면 에러가 난다!
    • 이 폴더에 next 프로젝트를 만든다.
  • next 프로젝트의 기본 파일들을 생성해 보자.
    • 이 명령어를 치면 next-env.d.ts 파일과 .next 폴더가 생성된다.
  • next dev
  • pages 폴더 안에 _app.tsx, _document.tsx, index.tsx 파일을 만들어 준다.
    • _app.tsx는 모든 페이지에 공통적으로 적용될 레이아웃, 글로벌 상태, 스타일 등을 설정할 수 있는 컴포넌트 (기본이 됨)
      • 클라 및 서버 모두에서 렌더링
      // pages/_app.tsx
      import type { AppProps } from 'next/app'
      // import '../styles/globals.css'
      
      export default function MyApp({ Component, pageProps }: AppProps) {
        return (
          <>
            <header>공통 헤더</header>
            <Component {...pageProps} />
            <footer>공통 푸터</footer>
          </>
        )
      }
      
    • _document.tsx 는 Next.js에서 기본 제공하는 HTML 문서(기본 구조)를 직접 제어한다. (<html>, <body>, <head> 같은 부분)
      • 언어 설정이나 google font 같은 외부 스타일 링크, 초기 스크립트 삽입
      // pages/_document.tsx
      import { Html, Head, Main, NextScript } from 'next/document'
      import { DocumentProps } from 'next/document'
      
      export default function Document(props: DocumentProps) {
        return (
          
            
              
              
      ) }
    • index.tsx 파일은 렌더링 시험하기 위해 만드는 기본 페이지 이다. 있어도 되고 없어도 되고…
    • import { FC } from 'react'; const Home: FC = () => { return <h1>Home</h1>; }; export default Home;
  • next dev 는 next 파일을 빌드하지 않고 바로 실행해보는 모드!

프로젝트 세팅하기

설정 파일 작성하기

tsconfig.json

  • node가 이 파일을 토대로 build를 함!
  • @tsconfig.json에서 사용되는 옵션들이다.
    /* Visit https://aka.ms/tsconfig to read more about this file */
    
        /* Projects */
        // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
        // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
        // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
        // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
        // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
        // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
    
        /* Language and Environment */
        "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
        // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
        // "jsx": "preserve",                                /* Specify what JSX code is generated. */
        // "libReplacement": true,                           /* Enable lib replacement. */
        // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
        // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
        // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
        // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
        // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
        // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
        // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
        // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
        // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */
    
        /* Modules */
        "module": "commonjs",                                /* Specify what module code is generated. */
        // "rootDir": "./",                                  /* Specify the root folder within your source files. */
        // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
        // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
        // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
        // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
        // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
        // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
        // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
        // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
        // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
        // "rewriteRelativeImportExtensions": true,          /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
        // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
        // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
        // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
        // "noUncheckedSideEffectImports": true,             /* Check side effect imports. */
        // "resolveJsonModule": true,                        /* Enable importing .json files. */
        // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
        // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
    
        /* JavaScript Support */
        // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
        // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
        // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
    
        /* Emit */
        // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
        // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
        // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
        // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
        // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
        // "noEmit": true,                                   /* Disable emitting files from a compilation. */
        // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
        // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
        // "removeComments": true,                           /* Disable emitting comments. */
        // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
        // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
        // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
        // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
        // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
        // "newLine": "crlf",                                /* Set the newline character for emitting files. */
        // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
        // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
        // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
        // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
        // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    
        /* Interop Constraints */
        // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
        // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
        // "isolatedDeclarations": true,                     /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
        // "erasableSyntaxOnly": true,                       /* Do not allow runtime constructs that are not part of ECMAScript. */
        // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
        "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
        // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
        "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    
        /* Type Checking */
        "strict": true,                                      /* Enable all strict type-checking options. */
        // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
        // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
        // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
        // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
        // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
        // "strictBuiltinIteratorReturn": true,              /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
        // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
        // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
        // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
        // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
        // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
        // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
        // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
        // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
        // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
        // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
        // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
        // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
        // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
    
        /* Completeness */
        // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
        "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  • tsconfig.json은 nest, next 동시에 적용할 수 있는 옵션들이 좋다고 한다.
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "esnext",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "lib": ["dom", "dom.iterable", "esnext", "DOM"],
    "allowJs": true,
    "strict": false,
    "noEmit": false,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "preserveConstEnums": true,
    "paths": {
      "@/*": ["src/*"]
    },
    "types": ["node"]
  },
  "exclude": ["node_modules", "dist", "jest"],
  "declaration": true,
  "emitDecoratorMetadata": true,
  "target": "es2017",
  "incremental": true,
  "noImplicitAny": false,
  "strictBindCallApply": false,
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tailwind.config.js"]
}

 

tsconfig.build.json 을 tsconfig.server.json으로 수정하기

  • 저 이름을 쓰면 server가 빌드될 때 tsconfig.server.json을 참고하여 빌드를 한다.
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "dist",
    "declaration": true,
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "experimentalDecorators": true, 
    "emitDecoratorMetadata": true,
    "isolatedModules": false,
    "noEmit": false,
    "allowJs": false
  },
  "include": ["./src/**/*.ts", "./src/**/**/*.ts", "./@types/**/*.d.ts"],
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts", ".next"]
}

nest-cli 설정하기

{
  "$schema": "<https://json.schemastore.org/nest-cli>",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true
  }
}
  • 옵션을 보면
    • "sourceRoot": "src", : Nestjs 프로젝트의 소스 루트
    • "entryFile": "main", : 애플리케이션의 진입점(entry point) 파일 이름 (main.ts)
    • "outDir": "dist", : 빌드한 js 결과물을 저장할 폴더 경로 지정
    • "deleteOutDir": true : 빌드하기 전 outDir을 삭제 → dist 폴더가 있다면 nest가 먼저 지우고 새로 빌드

pakage.json 확인하기

  • 내가 설치한 모듈들과 앱을 구동하는 script 등이 저장되는데.. 기본 script들은 nest앱만 구동한다.
  • script를 고쳐보자
  "scripts": {
    "prebuild": "rimraf dist",
    "prebuild:next": "rimraf .next",
    "build": "nest build",
    "build:next": "next build --no-lint",
    "build:nest": "nest build --path ./tsconfig.server.json",
    "format": "prettier --write \\"src/**/*.ts\\" \\"test/**/*.ts\\"",
    "start": "node ./dist/server/main.js",
    "start:next": "next dev",
    "start:dev": "nest start --path ./tsconfig.server.json --watch",
    "start:debug": "nest start --path ./tsconfig.server.json --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \\"{src,apps,libs,test}/**/*.ts\\" --fix",
    "rimraf": "sudo ./node_modules/rimraf/bin.js"
  },

next.config.js 만들기

  • nextjs 앱을 만들면 원래 생성되는 파일이다.
  • next를 빌드할 때 이 것을 참고한다.
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const nextConfig = {
  poweredByHeader: false,
  env: {},
  compiler: {
    // Enables the styled-components SWC transform
    styledComponents: true,
    distDir: '.next',
  },
};

exports.default = nextConfig;

 

+ Recent posts