cra 없이 리액트 개발환경 직접 구축해보기(3) (Webpack)

jaehan·2023년 2월 3일
0

React

목록 보기
25/33
post-thumbnail

Webpack이란

모듈 번들링 -> html 파일에 들어가는 자바스크립트 파일들을 하나의 자바스크립트 파일로 만들어주는 방식
웹팩은 다수의 자바스크립트 파일을 하나의 자바스크립트 파일로 만들어 주는 것이다.

생긴 이유

웹 페이지 방식이 단일 페이지 어플리케이션으로 전환되면서 한 페이지에 자바스크립트 파일이 너무 많아 져서 자바스크립트 파일을 하나로 관리하기 위해 나온게 웹팩이다.

사용해보기

파일 생성

  1. 폴더를 하나 만들고 npm init -y 명령어로 package.json 파일을 만든다
  2. index.html을 만든다
  3. src 폴더를 만들어 그 안에 index.js, Button.js를 만든다
  4. npm install webpack webpack-cli react react-dom 설치

index.html

<html>
  <body>
    <h2>cra 없이 만든 조아요 페이지</h2>
    <div id="react-root"></div>
    <script src="dist/main.js"></script>
  </body>
</html>

index.js

import React from "react";
import ReactDOM from "react-dom";
import Button from "./Button.js";

function Container() {
  return React.createElement(
    "div",
    null,
    React.createElement("p", null, "버튼을 클릭해 주세요"),
    React.createElement(Button, { label: "좋아요" }),
    React.createElement(Button, { label: "싫어요" })
  );
}

const domContainer = document.querySelector("#react-root");
ReactDOM.render(React.createElement(Container), domContainer);

Button.js

import React from "react";

export default function Button(props) {
  return React.createElement("button", null, props.label);
}

웹팩 으로 합치기

npx webpack을 사용하면 dist 폴더가 생기면서 그안에 main.js가 생긴다.
❗️이 main.js가 index.js랑 Button.js가 합쳐진 자바스크립트 파일이다

index.html을 실행시켜보면 아래와 같은 결과가 나온다

0개의 댓글