부트캠프/TIL

webpack으로 리액트 프로젝트 배포하기

하이고니 2023. 3. 22. 20:16

 

create-react-app 을 사용하지 않고 하나하나 설치해서 배포까지 해보겠습니다. 화이팅!

 

경로는 이런 식입니다.

 

 

1. npm init

$ npm init -y

 

2. 웹팩과 웹팩 cli 설치

 

$ npm i -D webpack webpack-cli

 

3. 바벨 설치 (JSX 읽어야 하니까)

 

$ npm i -D babel-loader @babel/core @babel/preset-env @babel/preset-react

 

4. 최상위 경로에 webpack.config.js 파일 만들기

 

 

5. webpack.config.js 설정

 

const path = require("path");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "app.bundle.js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              ["@babel/preset-env"],
              ["@babel/preset-react", { runtime: "automatic" }],
            ],
          },
        },
      },
    ],
  },
};

 

6. 리액트 설치

 

$ npm i react react-dom

 

7. css-loader, style-loader 설치

 

$ npm i -D css-loader style-loader

 

8. styled-components 설치 (optional)

 

$ npm i styled-components

 

9. axios 설치 (optional)

 

$ npm i axios

 

10. html webpack plugin 설치

 

$ npm i -D html-webpack-plugin

 

이쯤에서 webpack.config.js 파일 설정 추가

 

const path = require("path");
// 플러그인은 빌드할 때 추가적인 기능을 제공하는 것이기 때문에
// 웹팩이 인식할 수 있게 위에서 require로 불러와야 함

const HtmlWebpackPlugin = require("html-webpack-plugin");
// 로더는 빌드할 때 웹팩이 알아서 인식하고 적용함

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "app.bundle.js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              ["@babel/preset-env"],
              ["@babel/preset-react", { runtime: "automatic" }],
            ],
          },
        },
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          }
        ]
      }
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "public", "index.html")
    })
  ]
};

 

 

11. file-loader 설치 (png, jpeg 등 이미지 파일까지 빌드해야 하는 경우)

 

$ npm i -D file-loader

 

11-1.

 

public 폴더에 이미지 파일이 있을 때 그냥 <img src="경로" /> 요런 식으로 썼던 코드가 있을 수 있다.

하지만 빌드할 때 그 경로를 읽을 수는 없으므로,

 

import myImg from '../public/myimage.png'

 

이런 식으로 임포트해서 <img src={myImg} /> 요렇게 써야 한다.

 

여기까지 하면 client는 완료.

 

 

잘 나온다.

 

 

이제 서버.. 오 서버가 생각보다 별 게 없네요

 

서버 세팅

 

1. npm init

 

$ npm init -y

 

2. nodemon, cors, dompurify, express, jsdom, morgan, uuid 설치 (사용하지 않는 것은 제외) 

 

$ npm i '설치할 패키지 이름'

 

 

 

이제 깃헙 배포 도전

 

0. 깃헙은 docs 폴더 안에 들어있는 파일들만 읽기 때문에 경로를 수정해줘야 함.

 

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

module.exports = {
  entry: "./src/index.js",
  output: {
  // 이부분
    path: path.resolve(__dirname, "docs"),
    filename: "app.bundle.js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              ["@babel/preset-env"],
              ["@babel/preset-react", { runtime: "automatic" }],
            ],
          },
        },
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          }
        ]
      }
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "public", "index.html")
    })
  ]
};

 

1. 깃 레포지토리 생성

 

2. 최상위 경로에 .gitignore 파일 생성

 

3. 이 페이지에서 내가 사용할 것 (react, Node 등) 입력하고 생성된 코드를 .gitignore 파일에 입력

 

https://www.toptal.com/developers/gitignore

 

gitignore.io

Create useful .gitignore files for your project

www.toptal.com

 

예시

 

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

### Node Patch ###
# Serverless Webpack directories
.webpack/

# Optional stylelint cache

# SvelteKit build / generate output
.svelte-kit

### react ###
.DS_*
**/*.backup.*
**/*.back.*

node_modules

*.sublime*

psd
thumb
sketch

# End of https://www.toptal.com/developers/gitignore/api/react,node

 

4. 프로젝트 git init 

 

$ git init

 

5. 원격 레포지토리 연결 (이건 깃헙에서 레포지토리 생성하면 안내 코드에 나와 있음. 그거 복붙하면 됨.)

 

$ git remote add origin [레포지토리 URL]

 

7. git status로 node_modules처럼 커밋하고 싶지 않은 애들 빠져있는지 확인

 

8. add

 

$ git add .

 

9. commit

 

$ git commit -m "커밋 메시지"

 

10. push

 

git push -u origin main

 

이렇게 하면 push까지 끝난다.

 

11. 레포지토리 settings - pages에서 

 

 

위와 같이 세팅 후 save

 

 

12. 배포 완료

 

 

 

 

+ node_modules 같이 push 해버렸다...!! 이런 문제 상황 발생 시

 

 

일단 

 

$ rm -rf .git

 

입력해서 git 파일 지우고

 

$ git remote remove [원격 저장소 이름. 보통 origin]

 

해서 연결 끊은 다음에

 

$ git init

 

해보세요..

 

$ git status

 

입력했을 때

 

요런 식으로 커밋한 적 없다고 나오면 된 겁니다..