프로젝트 초기 구성
이 챕터에서는 프로젝트 생성부터 웹팩 기초 세팅 및 타입스크립트 설정 및 디렉토리 구조를 설명합니다.
문서는 npm으로 작성됐지만 yarn이나 pnpm을 사용하셔도 무관합니다.
CRA를 사용하지 않는 프로젝트이며,
CRA 프로젝트의 eject를 사용한 설정 및 craco 라이브러리를 사용한 설정은 다루지 않습니다.
- Terminal
mkdir my-app mkdir src public
npm init --y
npm install react react-dom
react-dom
- render()와 createPortal() 등이 포함된 패키지
npm install typescript @types/react @types/react-dom -D
@types/react
- react에 대한 타입 정의가 포함되어 있는 패키지
@types/react-dom
- react-dom에 대한 타입 정의가 포함되어 있는 패키지
npm install @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript -D
@babel/core
- 바벨을 사용하는데 필요한 패키지
@babel/preset-env
- Babel플러그인과 polyfill을 자동으로 관리하여 최신 javascript를 사용하게 해주는 패키지
@babel/preset-react
- react 문법을 변환하는데 필요한 규칙을 정의한 패키지
@babel/preset-typescript
- typescript 문법을 변환하는데 필요한 규칙을 정의한 패키지
npm install webpack webpack-cli webpack-dev-server -D
webpack
- 여러 개의 파일을 하나의 파일로 합쳐주는 모듈 번들러
webpack-cli
- 웹팩을 터미널 명령어로 실행할 수 있도록 도와주는 패키지
webpack-dev-server
- 기본적인 웹 서버를 구동시킬 수 있고, live reloading 기능도 제공하는 패키지
npm install html-webpack-plugin clean-webpack-plugin -D
html-webpack-plugin
- webpack 번들이 제공하는 HTML 파일 생성을 단순화하는 패키지
clean-webpack-plugin
- 빌드파일은 아웃풋 경로에 모이는데 기존파일이 남아있는경우 이전 빌드파일을 지워주는 패키지
npm install babel-loader -D
babel-loader
- 웹팩과 바벨을 사용해서 javascript 파일을 transpile하는 패키지
디렉토리 구조 및 필요한 설정 파일들을 설명하는 구간입니다.
- SRC
// App.tsx const App = () => { return <div>Webpack boilerPlate</div>; }; export default App;
리액트 18에서는 index를 작성하는 문법이 달라졌습니다.
17버전으로 작성하실 경우 콘솔에 에러가 뜨기때문에 본인의 프로젝트 버전에 맞추시면 됩니다.
// react 17 // index.tsx import ReactDOM from "react-dom"; import App from "./App"; ReactDOM.render(
// react 18 // index.tsx import { createRoot } from 'react-dom/client'; import App from './App'; createRoot(document.getElementById('root') as HTMLElement).render(
// assets.d.ts declare module '.png'; declare module '.jpg'; declare module '.ico'; declare module '.svg';
- PUBLIC
// index.html
- ROOT
// webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { entry: path.resolve(__dirname, '..', ./src/index'), resolve: { extensions: ['.js', '.ts', '.tsx'], }, output: { path: path.resolve(__dirname, '..', ./build'), filename: 'bundle.js', }, module: { rules: [ { test: /\.(ts|js)x?$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', }, ], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, '..', ./public/index.html'), }), new CleanWebpackPlugin(), ], };
// package.json { "name": "webpack-boilerplate", "version": "1.0.0", "main": "src/index.tsx", "license": "MIT", }
// .babelrc { "presets": [ "@babel/preset-env", [ "@babel/preset-react", { "runtime": "automatic" } ], "@babel/preset-typescript" ], }
// .gitignore build node_modules
// tsconfig.json { "compilerOptions": { /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "ES5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */, "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, "lib": [ /* Specify library files to be included in the compilation. */ "DOM", "ESNext" ], // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ "jsx": "react-jsx" /* 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": "./", /* Redirect output structure to the directory. */ // "rootDir": "./", /* 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": [], /* 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. */, "resolveJsonModule": true }, "include": [ "src/**/*" ] }
tsconfig 파일의 경우 개인의 기호에 맞게 커스텀해도 무방하며,
팀으로 작업할 경우 팀원들간의 컨벤션을 맞추는것이 좋습니다.
설정 옵션의 자세한 설명은 아래 링크에 자세하게 설명되어 있습니다.
tsconfig guide - Root fields
tsconfig guide - Type Checking
tsconfig guide - Modules
tsconfig guide - Emit