[React] 웹팩으로 빌드하고 깃허브 페이지 배포하기

young·2022년 7월 26일
2

Learn more

목록 보기
18/22

create-react-app 없이 react app 만들고,
webpack으로 빌드 후 깃허브 배포하기

깃허브 링크

https://github.com/y0ungg/react-webpack-bundling


🧩 초기 세팅

package.json 및 node_modules 생성

$ npm init : package.json 파일 생성
(이때 main: index.jsx)

$ npm i -D --save 명령어로 아래 라이브러리 install

    "@babel/core": "^7.18.9",
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/preset-env": "^7.18.9",
    "@babel/preset-react": "^7.18.6",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.7",
    "babel": "^6.23.0",
    "babel-loader": "^8.2.5",
    "clean-webpack-plugin": "^4.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^6.7.1",
    "dotenv": "^16.0.1",
    "dotenv-webpack": "^8.0.0",
    "eslint": "^8.20.0",
    "html-webpack-plugin": "^5.5.0",
    "react": "^18.2.0", //react도 반드시 설치 필요!
    "react-dom": "^18.2.0", //react-dom도 반드시 설치 필요!
    "react-refresh": "^0.14.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"

package.json의 scripts 객체 안에 "build": "webpack --config webpack.config.js",를 작성해주면 npm run build 명령어로 npx webpack --config webpack.config.js을 할 수 있게 된다.

If a webpack.config.js is present, the webpack command picks it up by default. We use the --config option here only to show that you can pass a configuration of any name. This will be useful for more complex configurations that need to be split into multiple files. -공식문서

✔️ index.jsx 생성

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import './style.css' //css파일도 불러오기

ReactDOM.render(<App />, document.getElementById('root'));

✔️ App.jsx 생성

import React from "react";

const App = () => {
    return (
        <div id="root">
            <h1>hello</h1>
        </div>
    )
}

export default App;

index의 하위 컴포넌트들에도 react를 import 해오지 않으면 에러가 발생한다.

✔️ index.html 생성

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
    <script type="module" src="./index.jsx"></script>
</body>
</html>

script 태그의 type="module"은 갖은 에러를 마주한 끝에 작성한 내용이다.
없이 시작하고 에러 내용에 따라서 작성하면 될 것이다.

✔️ style.css 생성

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

h1 {
    color: blueviolet;
}

위의 네 파일은 같은 디렉토리에 만들었다.
이제 webpack.config.js 생성하고 연결만 시켜주면 된다




🧩 webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development', // 또는 production
    resolve: {
        extensions: ['.jsx', '.js'] // a Webpack library that helps locate imported modules. 
    } ,
    entry: { //시작하는 파일 넣을 것
        app: ['./index.jsx']
    },
    module: { //loaders
        rules: [
            {
              test: /\.css$/i,
              use: ["style-loader", "css-loader"],
              exclude: /node_modules/, //제외함
            },
            {
                test: /\.jsx$/,
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env', '@babel/preset-react'],
                },
            }
          ],
    },
    plugins: [new HtmlWebpackPlugin({
        template: path.resolve(__dirname, "./index.html") //template도 꼭 작성해야 함!!
      })],
    output: {
        path: path.resolve(__dirname, "docs"), //깃허브 페이지 배포를 위해 docs로 설정해주었다.
        filename: "app.js",
      },
};

이렇게 보면 뚝딱 작성한 것 같지만 여러 에러를 겪고 수정한 내용이다...
파일 위치와 확장자 조심할 것, 이름 제대로 쓸 것!


깃허브 배포하기

원하는 대로 웹팩을 커스텀하고, npm run build를 하면
output path에 번들 파일이 저장된다.

  1. 해당 파일만 깃허브 레포지토리 root 디렉토리에 push 해서
    pages 배포 옵션을 /root로 설정하거나,

  2. output path를 docs로 설정하고 해당 폴더를 포함하여 깃허브 레포지토리에 push하고
    pages 배포 옵션을 /docs로 설정하면

번들 파일을 바탕으로 깃허브 페이지 배포를 할 수 있게 된다.

profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글