한윤석 개발 블로그

배운 것을 적는 블로그입니다.

Webpack 시작하기

등록일: 2019-02-05
수정일: 2019-02-05

Basic Setup

디렉토리를 만들고 npm을 초기화 한 후 webpack을 local에 설치합니다.

mkdir webpack-demo && cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev

src/index.js와 index.html파일을 만들어줍니다.

function component() {
  let element = document.createElement('div');

  // Lodash, currently included via a script, is required for this line to work
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());
<!doctype html>
<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.16.6"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>

index.js를 살펴보면 global변수_가 쓰인것을 확인할 수 있습니다. 하지만 _가 어디에서도 선언되지 않아 올바르게 동작하지 않습니다.

Creating a Bundle

우리가 작성하는 source코드와 실체 출시 코드를 분리하기위해먼저 index.html/dist/index.html로 옮겨봅시다.

그리고 다음과 같이 입력해 lodash를 설치해 줍시다

npm install lodash

이제 lodash를 import합니다.

src/index.js

import _ from 'lodash';

dist/index.html에서 불러왔던 lodash와 index.js를 삭제하고 우리가 번들링 할 파일로 바꿔줍니다.

  <!doctype html>
  <html>
   <head>
     <title>Getting Started</title>
-    <script src="https://unpkg.com/lodash@4.16.6"></script>
   </head>
   <body>
-    <script src="./src/index.js"></script>
+    <script src="main.js"></script>
  </html>
   </body>

이제 번들링 하기위해 다음과같이 실행합니다. npx webpack은 ./node_modules/.bin/webpack을 실행합니다.

npx webpack

실행하면 dist/main.js가 생긴것을 확인할 수 있고 dist/index.html을 실행하면 Hello webpack이 출력되는것을 확인할 수 있습니다.

Using a Configuration

Version 4부터는 특별한 설정이 필없지만, 특정한 설정이 필욯라 경우 configuration file을 통해 설정이 가능합니다.

project

  webpack-demo
  |- package.json
+ |- webpack.config.js
  |- /dist
    |- index.html
  |- /src
    |- index.js

webpack.config.js

const path = require('path');

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

다음과같이 실행할 수 있습니다.

npx webpack --config webpack.config.js

webpack.config.js파일이 있으면 기본으로 --config flag없이 config file을 실행 합니다.

NPM Scripts

webpack을 편하게 실행하기 위해 package.json에 npm script들을 추가할 수 있습니다.

 {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9"
    },
    "dependencies": {
      "lodash": "^4.17.5"
    }
  }

이렇게 설정하면 npm run build커맨드로 webpack을 실행할 수 있습니다. 혹은 다른 flag가 있더라도 편하게 실행할 수 있습니다.

source

https://webpack.js.org/guides/getting-started/


자바스크립트로 직접 만들면서 배우는 - 자료구조와 알고리즘 강의 바로 가기
기계인간 이종립, 소프트웨어 개발의 지혜 - Git 강의 바로 가기

코드숨에서 매주 스터디를 진행하고 있습니다. 메일을 등록하시면 새로운 스터디가 시작될 때 알려드릴게요!