Create React Project [webpack]

homewiz·2023년 11월 21일

React [Webpack]

목록 보기
1/11
post-thumbnail

1. INTRO

CRA를 이용 하지 않고 웹팩으로 리액트 프로젝트 세팅을 한다.


2. Create Project - yarn

> mkdir ProjectName
> cd ProjectName
> yarn init
yarn init v1.22.19
question name (test4):
question version (1.0.0):
question description:
question entry point (index.js):
question repository url:
question author:
question license (MIT):
question private:         
success Saved package.json
Done in 6.64s.
// 본인 입맛에 맞게 답변을 하면되고 귀찮으면 enter 또는 yarn init -y

위 과정을 통해 Project root > package.json이 생성된다.

{
  "name": "test4",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT"
}

3. Install Packages

3-1. install react

yarn add react react-dom

  • React는 View를 만들기위한 라이브러리
  • ReactDOM은 UI를 실제로 브라우저에 렌더링 할 때 사용하는 라이브러리

3-2. install webpack

yarn add -D webpack webpack-cli webpack-dev-server eslint html-webpack-plugin eslint-webpack-plugin

  • webpack: javaScript application staic module buddler
    웹팩을 사용하면 응용 프로그램을 구성 요소로 분할하고 이를 종속성 관리를 통해 정적 에셋으로 변환하여 번들링할 수 있다.

  • webpack-cli: webpack commnd interface
    웹팩 빌드 및 관련명령어를 터미널에서 사용할 수 있다.

  • webpack-dev-server: dev server
    실시간으로 변경되는 소스를 확인 하고 디버깅 할수 있다.

  • eslint: 자바스크립트 코드에서 발견되는 문제시되는 패턴들을 식별하기 위한 정적 코드 분석 도구.

  • html-webpack-plugin: 웹팩 빌드 시 자동으로 HTML 파일을 생성.
    웹팩 빌드에서 생성된 JavaScript나 CSS 파일을 HTML 파일에 자동으로 추가할 수 있습니다.

  • eslint-webpack-plugin: ESLint 규칙을 만족하지 못하는 코드가 있으면 터미널과 콘솔창에 에러를 발생

3-3. install babel

  • Babel : JavaScript 최신 문법을 구형 브라우저에서도 실행 가능한 ES5로 변환 도구.

yarn add -D @babel/core @babel/preset-env @babel/preset-react babel-loader

  • @babel/core: Babel Core Package
  • @babel/preset-env: 이 preset은 최신 JavaScript 문법을 사용하여 작성된 코드를 지원할 브라우저 환경에 맞게 변환해줍니다. 브라우저 지원 목록을 설정하고 필요한 폴리필을 추가하여 최신 문법을 구형 브라우저에서도 실행 가능하게 만들어줍니다.
  • @babel/preset-react: 이 preset은 React 애플리케이션에서 JSX 문법을 사용할 수 있게 해줍니다. JSX는 JavaScript 내에서 HTML을 작성할 수 있게 해주는 문법으로, React 애플리케이션을 개발할 때 필수적인 도구입니다.
  • babel-loader: Webpack에서 바벨을 사용 하기 위한 로더

4. Set Configs

4.1 create .eslintrc.json

yarn eslint --init
커맨드를 이용하여 상황에 맞게 설정 해준다.
...
Which framework does your project use? · react 이문서는 리액트니깐
What format do you want your config file to be in? · JSON 기호에 맞게
...
Which package manager do you want to use? · yarn 이문서는 yarn으로 하니깐
...

yarn eslint --init
yarn run v1.22.19
$ C:\work\sources\test1\node_modules\.bin\eslint --init
You can also run this command directly using 'npm init @eslint/config'.
√ How would you like to use ESLint? · problems
√ What type of modules does your project use? · esm
√ Which framework does your project use? · react
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser
√ What format do you want your config file to be in? · JSON
The config that you've selected requires the following dependencies:

eslint-plugin-react@latest
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · yarn
Installing eslint-plugin-react@latest
[1/4] Resolving packages...
[2/4] Fetching packages...
warning Pattern ["eslint-plugin-react@^7.33.2"] is trying to unpack in the same destination "C:\\Users\\USER\\AppData\\Local\\Yarn\\Cache\\v6\\npm-eslint-plugin-react-7.33.2-69ee09443ffc583927eafe86ffebb470ee737608-integrity\\node_modules\\eslint-plugin-react" as pattern ["eslint-plugin-react@^7.27.1"]. This could result in non-deterministic behavior, skipping.
[3/4] Linking dependencies...
warning "eslint-config-react-app > eslint-plugin-flowtype@8.0.3" has unmet peer dependency "@babel/plugin-syntax-flow@^7.14.5".
warning "eslint-config-react-app > eslint-plugin-flowtype@8.0.3" has unmet peer dependency "@babel/plugin-transform-react-jsx@^7.14.9".
warning "eslint-config-react-app > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
warning "react-dev-utils > fork-ts-checker-webpack-plugin@6.5.3" has unmet peer dependency "typescript@>= 2.7".
[4/4] Building fresh packages...
success Saved 1 new dependency.
info Direct dependencies
└─ eslint-plugin-react@7.33.2
info All dependencies
└─ eslint-plugin-react@7.33.2
Successfully created .eslintrc.json file in C:\work\sources\test1
Done in 23.00s.

4-2. create webpack.config.js

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ESLintPlugin = require("eslint-webpack-plugin");

module.exports = (env, argv) => {
  const prod = argv.mode === "production";

  return {
    mode: prod ? "production" : "development",
    devtool: prod ? "hidden-source-map" : "eval",
    entry: {main: "./src/index.js"},
    output: {
      path: path.join(__dirname, "/dist"),
      filename: "[name].js",
      clean: true
    },
    devServer: {
      port: 3000,
      hot: true
    },
    resolve: {
      extensions: [".js", ".jsx", ".ts", ".tsx"]
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx|ts|tsx)$/,
          use: ["babel-loader"]
        }
      ]
    },
    plugins: [
      new webpack.ProvidePlugin({
        React: "react"
      }),
      new HtmlWebpackPlugin({
        template: "./public/index.html",
        minify:
          process.env.NODE_ENV === "production"
            ? {
                collapseWhitespace: true, // 빈칸 제거
                removeComments: true // 주석 제거
              }
            : false
      }),
      new ESLintPlugin({
        // Plugin options
        extensions: ["js", "mjs", "jsx", "ts", "tsx"],
        eslintPath: require.resolve("eslint"),
        cache: true,
        baseConfig: {
          rules: {"react/react-in-jsx-scope": "error"}
        }
      })
    ]
  };
};

4.3 create babel.config.js

// root/babel.config.js
module.exports = {
  presets: ["@babel/preset-react", "@babel/preset-env"],
};

4.4 package.json

...
add
"scripts": {
    "dev": "webpack-dev-server --mode=development --open --hot --progress",
    "build": "webpack --mode=production  --progress",
    "start": "webpack --mode=development  --progress"
  }
...

5. Create Source

5-1 ./public/index.html

<!-- ./public/index.html -->
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Pragma" content="no-cache" />
    <title>First React</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

5-2 ./src/index.js

// ./src/index.js
import React, { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const root = createRoot(document.getElementById("root"));
root.render(
  // StricMode 개발 초기에 구성 요소의 일반적인 버그를 찾을 수 있습니다.
  <StrictMode>
    <App />
  </StrictMode>
);
  • StricMode
    전체 앱에 대해 StricMode 활성화
    앱의 일부에 대해 StricMode 활성화
    개발 중 이중 렌더링으로 발견된 버그 수정
    개발 중 Effects를 다시 실행하여 발견된 버그 수정
    엄격 모드로 활성화된 지원 중단 경고 수정

5-3 ./src/App.jsx

import React from "react";

const App = () => {
  return <div>This is App.jsx</div>;
};

export default App;

6. Execution

yarn dev

yarn run v1.22.19
$ webpack-dev-server --mode=development --open --hot --progress
<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:3000/
<i> [webpack-dev-server] On Your Network (IPv4): http://192.168.0.6:3000/
<i> [webpack-dev-server] Content not from webpack is served from 'C:\work\sources\test4\public' directory
10% building 0/3 entries 43/44 dependencies 19/30 modules[BABEL] Note: The code generator has deoptimised the styling of C:\work\sources\test4\node_modules\react-dom\cjs\react-dom.development.js as it exceeds the max of 500KB.
asset main.js 1.25 MiB [emitted] (name: main)
asset index.html 310 bytes [emitted]
runtime modules 27.4 KiB 13 modules
modules by path ./node_modules/ 1.15 MiB
  modules by path ./node_modules/webpack-dev-server/client/ 78.4 KiB 16 modules
  modules by path ./node_modules/webpack/hot/*.js 5.34 KiB 4 modules
  modules by path ./node_modules/html-entities/lib/*.js 115 KiB 4 modules
  modules by path ./node_modules/react-dom/ 844 KiB 3 modules
  modules by path ./node_modules/react/ 94.9 KiB 2 modules
  modules by path ./node_modules/scheduler/ 19.5 KiB 2 modules
  ./node_modules/ansi-html-community/index.js 4.57 KiB [built] [code generated]
  ./node_modules/events/events.js 14.3 KiB [built] [code generated]
modules by path ./src/ 524 bytes
  ./src/index.js 370 bytes [built] [code generated]
  ./src/App.jsx 154 bytes [built] [code generated]
webpack 5.89.0 compiled successfully in 5001 ms

!!! 위처럼 정상 실행 되지만 컴파일 중간에 아래와 같은 경고 메세지가 발생한다.
CRA를 이용해서 빌드시에도 같은 메세지가 발생

One of your dependencies, babel-preset-react-app, is importing the
"@babel/plugin-proposal-private-property-in-object" package without
declaring it in its dependencies. This is currently working because
"@babel/plugin-proposal-private-property-in-object" is already in your
node_modules folder for unrelated reasons, but it may break at any time.

babel-preset-react-app is part of the create-react-app project, which
is not maintianed anymore. It is thus unlikely that this bug will
ever be fixed. Add "@babel/plugin-proposal-private-property-in-object" to
your devDependencies to work around this error. This will make this message
go away.

해당 package가 없다고 하니 설치 해준다.

yarn add -D @babel/plugin-proposal-private-property-in-object


7. Output Tree

├─ public
	└─ index.html
├─ src
    ├─ App.jsx
    └─ index.js
├─ .eslintrc.json
├─ babel.config.js
├─ package.json
├─ jsconfig.json
├─ yarn.lock
└─ webpack.config.js

8. Quick

yarn init -y
yarn add react react-dom
yarn add -D webpack webpack-cli webpack-dev-server html-webpack-plugin eslint eslint-webpack-plugin @babel/core @babel/preset-env @babel/preset-react babel-loader @babel/plugin-proposal-private-property-in-object
yarn eslint --init

리눅스 터미널 또는 vscode git bash 터미널에서 해주세요.
실행 불가 또는 이해가 안될경우 위 1~7 하나씩 수행

mkdir public && mkdir src && touch src/index.js && touch src/App.jsx && touch public/index.html && touch webpack.config.js && touch babel.config.js

9. SOURCE

https://bitbucket.org/code7004/react-webpack/src/465265e9339ec8964083f8b027fa2de9cf62615c/

0개의 댓글