웹팩 이용해 빌드하기 (바닐라 JS)

hzn·2022년 11월 24일
0

React

목록 보기
6/15
post-thumbnail

최종 디렉토리 구조


1. package.json

1) package.json 파일 있는지 확인

  • 없으면 🦄 npm init -y로 생성

2) script에 build 추가

  • npm run build로 webpack이 실행되도록 추가
    {
      "name": "fe-sprint-my-agora-states-reference",
      "version": "1.0.0",
      "description": "",
      "main": "data.js",
      "scripts": {
        "build": "webpack", // 👉🏽 build 추가
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "repository": {
        "type": "git",
        "url": "git@github.com-Pikadev1771:Pikadev1771/fe-sprint-my-agora-states-reference.git"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "css-loader": "^6.7.2",
        "html-webpack-plugin": "^5.5.0",
        "style-loader": "^3.3.1",
        "webpack": "^5.75.0",
        "webpack-cli": "^5.0.0"
      }
    }

2. entry 파일

  • 보통 ./src/index.js (기본값)
    (여기서는 ./script.js)

1) 디펜던시 export 하기

  • 디펜던시 파일에서 export 해주고

data.js

const agoraStatesDiscussions = [
  {
    id: 'D_kwDOHOApLM4APjJi',
    ...
module.exports = agoraStatesDiscussions; // 모듈 export 하기

2) entry 파일에 디펜던시 불러오기

  • entry 파일(script.js)에서 불러오기

script.js

import './style.css'; // css
import agoraStatesDiscussions from './data.js'; // 디펜던시 모듈 불러오기
...

3. webpack.config.js

1) 웹팩 설치하기

  • devDependency 옵션을 설정하고 설치
 🦄 npm install -D webpack webpack-cli

2) webpack.config.js 파일 설정하기

  • 처음에는 entry ,output 정도만 설정해놓고
const path = require('path'); // path 모듈 불러오기

module.exports = {
  entry: './script.js', // entry 경로 지정
  output: {
    path: path.resolve(__dirname, 'docs'), // 번들 파일 출력될 경로와 파일 이름 지정
    filename: 'app.bundle.js',
  },
};
  • Github Page로 배포하려면 output의 path를 'docs'로 설정해줘야 한다.
  • 로더, 플러그인 추가할 때마다 그에 맞춰서 수정
const path = require('path'); 
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 플러그인은 불러오기 필요

module.exports = {
  entry: './script.js',
  output: {
    path: path.resolve(__dirname, 'docs'),
    filename: 'app.bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],  // CSS 관련 로더 설정
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [                                // HTML 관련 플러그인 설정
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'index.html'),
    }),
  ],
};

4. Loder, Plugin 설치

1) 필요한 로더, 플러그인 설치하기

  • css-loader style-loader 설치
 🦄 npm i -D css-loader style-loader
  • html-webpack-plugin 설치
 🦄 npm i -D html-webpack-plugin

2) webpack.config.js에서 설정 수정하기

  • 설치한 로더, 플러그인에 맞춰서 webpack.config.js 수정

5. 번들링

  • 웹팩으로 번들링 하기
npx webpack

또는

npm run build

6. 결과물 확인하기

  • output 경로에 번들 파일 제대로 생성됐는지 확인

번들링 된 HTML 파일 확인

  • HTML 파일에 <script defer="defer" src="app.bundle.js"></script>로 번들 JS 파일 연결됐는지 확인

  • 아래 코드들 없는지 확인
    : CSS, 데이터 모듈 등 디펜던시는 모두 entry JS 안에 불러와서 번들 파일로 만들었고, 번들 JS 파일은 위 코드로 연결시켰으므로 아래 코드들은 필요 X)

    ( <head> 안에)
    <link rel="stylesheet" href="style.css">

    (<body> 아래)
    <script src="data.js"></script>
    <script src="script.js"></script>

docs > 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" />
    <title>My Agora States</title>
    <script src="https://..."></script>
    <script defer="defer" src="app.bundle.js"></script>
  </head>
  <body>
    <main>
      <h1>My Agora States</h1>
      ...
      </section>
    </main>
  </body>
</html>

0개의 댓글