[webpack] webpack 사용해보기

민수·2023년 2월 27일
0
post-thumbnail

webpack이란?

  • JavaScript를 위한 정적 모듈 번들러이다.
  • 여러 파일을 하나의 파일로 만들어주는 도구라고 볼 수 있다.

모듈이란?

  • 프로그램을 구성하는 구성 요소로 관련된 데이터와 함수를 하나로 묶은 단위를 말한다.
  • 하나의 JavaScript 파일이 하나의 모듈이라고 볼 수 있다.

번들러란?

  • 의존성 있는 모듈 코드를 하나 또는 여러개의 파일로 만들어 주는 도구이다.
  • 여러 파일에 작성된 코드들을 하나 또는 여러개의 파일에 새로 작성해 주는 도구라 볼 수 있다.

webpack 사용 이유

  • 코드의 가독성과 유지 보수를 위해 여러개로 나누어 놓았던 파일들을 브라우저에서 로드하려면 파일의 개수만큼 요청 응답이 일어난다.
  • 여러번의 요청과 응답은 트래픽을 많이 발생 시킨다.
  • SPA에서는 여러 파일이 필요하지 않기 때문에 작업 할 때만 분리해서 작업하고 배포할 때는 webpack을 이용해서 파일을 합치게 된다.

webpack 속성

webpack 4.0 부터는 기본적으로 내장된 기본 설정을 사용한다.
기본 설정을 사용하여 webpack을 실행하면 entry 파일을 찾고 output 파일을 생성하며 JavaScript, CSS 및 이미지 파일을 처리하는 로더를 사용하여 번들링을 해준다.

webpack.config.js 파일 작성

  • entry : 어떤 파일이 기준점인지 지정할 때 사용한다.
  • output : 어떤 디렉토리에 어떤 이름으로 번들을 내보낼 건지 지정할 때 사용한다.
  • loaders : 다양한 형태의 파일 또는 모듈을 변환할 때 사용한다.
  • plugins : 번들링 하기 전에 최적화를 하거나 파일을 생성 하는 등 다양한 작업을 할 때 사용한다.
  • mode : 내장된 환경별 최적화를 활성화 할 때 사용한다.

entry

  • webpack이 해당 파일이 의존하는 다른 모듈과 라이브러리를 찾아낼 수 있도록 엔트리 포인트를 지정한다.
  • 기본값은 ./src/index.js이다.
  • 기본 설정을 이용해서 webpack을 사용할 경우 번들링할 파일들을 src 디렉토리에 넣어 주어야하고 파일 이름을 index.js로 설정해주어야 한다.
module.exports = {
	entry: './src/index.js'
}

output

  • 생성된 번들을 내보낼 위치와 이 파일의 이름을 지정해준다.
  • 기본값으로 디렉토리는 ./dist이고 파일 이름은 main.js이다.
  • path.resolve는 경로를 합치고, 정규화하고 상대 경로를 절대 경로로 변환하는 메서드이다.
const path = require('path')

module.exports = {
	entry: './src/index.js',
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'main.js'
	}
}

loaders

  • webpack은 기본적으로 JavaScript와 JSON 파일만 이해한다.
  • loader를 사용해 다른 유형의 파일들을 처리할 수 있게 된다.
  • require()/import 문 내에서 .css로 설정된 파일을 발견하면 css-loader가 css 파일을 모듈화 하고 style-loader가 모듈화된 css 파일을 DOM에 적용해 스타일링을 한다.
const path = require('path')

module.exports = {
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'main.js'
	},
	module: {
		rules: [{
			test: /\.css$/,
			use: ["style-loader", "css-loader"],
		}]
	}
}

plugins

  • 번들을 최적화 하거나 이미지, 폰트, 오디오, 비디오 파일 등을 관리 하고 환경 변수 주입 등과 같은 작업을 수행한다.
  • 플러그인을 사용하려면 require()를 통해 플러그인을 요청하고 plugins 배열에 추가해야 한다.
  • 그리고 new 연산자를 호출해 플러그인 인스턴스를 생성해야 한다.
  • src/index.html 파일을 기준으로 새로운 HTML 파일을 dist 디렉토리에 만들어 준다.
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'main.js'
	}
	plugins: [
		new HtmlWebpackPlugin({
			template: "src/index.html",
			filename: "index.html"
		})
	]
}

mode

  • development, production, none으로 설정하면 내장된 환경별 최적화를 활성할 수 있다.
  • 기본값은 production이다.
module.exports = {
	mode: 'development'
}

아래와 같이 WARNING이 뜨는게 신경쓰이면 mode를 development로 변경해주면 된다.

$npx webpack

asset main.js 224 bytes [emitted] [minimized] (name: main)
./src/index.js 62 bytes [built] [code generated]
./src/home/go.js 43 bytes [built] [code generated]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

webpack 5.75.0 compiled with 1 warning in 156 ms

실습

  • 실습 환경 구성
mkdir -p webpack_practice/src/users
cd webpack_practice
npm init -y

webpack 기본 실행

  1. webpack 설치
npm install webpack webpack-cli
  1. 관련 패키지 설치
npm install react react-dom
  1. 예제 파일 생성
    src/index.js
const React = require("react");
const ReactDOM = require("react-dom");
const { name } = require("./users/user.js");

const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(React.createElement("div", null, `Hello ${name}`));

src/users/user.js

module.exports = {
  name: "cloudcoke",
};
  1. 번들링
npx webpack
  1. HTML 파일 생성 및 확인
    dist/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" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/javascript" src="./main.js"></script>
  </body>
</html>

webpack loaders 사용

  • CSS를 JavaScript로 번들링해서 스타일 적용하기
  1. webpack 설치
npm install webpack webpack-cli
  1. 로더 설치
    • css-loader : CSS 파일을 로드
    • style-loader : 로드한 CSS 파일을 DOM에 삽입하여 스타일을 적용
npm install css-loader style-loader
  1. 예제 파일 생성
    src/loader.js
import './loader.css'

src/loader.css

* {
  margin: 0;
  padding: 0;
  background: blue;
}
  1. webpack.config.js 설정
const path = require("path");

module.exports = {
  entry: "./src/loader.js",
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  output: {
    filename: "loader_output.js",
    path: path.join(__dirname, "dist"),
  },
};
  1. 번들링
npx webpack --config webpack.config.js
  1. HTML 파일 생성 및 확인
    dist/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" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/javascript" src="./loader_output.js"></script>
  </body>
</html>

webpack plugin 사용 - html-webpack-plugin

  • HTML 템플릿을 이용해 파일 생성하기
  1. webpack 설치
npm install webpack webpack-cli
  1. 플러그인인 설치
npm install html-webpack-plugin
  1. 예제 파일 생성
    src/plugin.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" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

src/plugin.js

const root = document.querySelector("#root");
root.innerHTML = "Hello World";
  1. webpack.config.js 설정
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/plugin.js",
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/plugin.html",
      filename: "plugin.html",
    }),
  ],
  output: {
    filename: "plugin_output.js",
    path: path.join(__dirname, "dist"),
  },
};
  1. 번들링
npx webpack --config webpack.config.js
  1. 생성된 HTML과 JavaScript 확인

webpack plugin 사용 - babel-loader

  1. webpack 설치
npm install webpack webpack-cli
  1. 로더 설치
npm install babel-loader
  1. babel 설치
npm install @babel/core
  1. babel preset 설치
npm install @babel/preset-env @babel/preset-react
  1. 관련 패키지 설치
npm install react react-dom
  1. 예제 파일 생성
    src/babel.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./app.js";

const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<App />);

src/app.js

import React from "react";

class App extends React.Component {
  render() {
    return <div>Webpack with Babel</div>;
  }
}

export default App;

src/babel.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" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
  1. .babelrc 설정
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}
  1. webpack.config.js 설정
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/babel.js",
  module: {
    rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: ["babel-loader"] }],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/babel.html",
      filename: "babel.html",
    }),
  ],
  output: {
    filename: "babel_output.js",
    path: path.join(__dirname, "dist"),
  },
  mode: "development",
};
  1. 번들링
npx webpack --config webpack.config.js
  1. 확인

참고

webpack 공식 문서

0개의 댓글