donaricano-btn

웹팩 기본 사용법 - webpack HelloWorld

(https://webpack.js.org/guides/getting-started/ 번역)


1. 웹팩 로컬 설치

- 웹팩을 설치하기 이전에 node.js를 설치해야한다.

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


2. 프로젝트 구조설정

1) 프로젝트 구조

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

2) src/index.js

- 해당 프로젝트에서 lodash 라이브러리를 사용했다.

function component() {
  var 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());

3) index.html

- lodash 라이브러리를 html문서에 직접 참조했다.

- webpack을 이용하여 차후에 script 소스들을 관리한다.

<!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>

4) package.json

  {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
+   "private": true,
-   "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9"
    },
    "dependencies": {}
  }

- private 을 true로 설정하고 엔트리 포인트인 main 을 제거하였다. 이유는 해당 소스가 배포될때 발생할 수 있는 사고를 미연에 방지 할 수 있다.


3. 번들 만들기

- webpack에서 모든 단위는 모듈에서 시작한다. js, image, css etc...모든 것은 모듈이 된다. 그리고 이런 모듈을 모아서 컴파일 단계를 거치면 하나의 묶음인 번들(bundle)이 생성되는 것이다. 

- 번들을 사용 함으로서 서버의 request를 줄이고 모듈들의 의존관리를 쉽게 할 수 있다

1) 프로젝트 구조 변경과 lodash 의존성 포함

- 앞의 예제에서 lodash를 html문서에 삽입하였지만 웹팩을 이용하여 의존성 관리가 되도록 추가한다

- --save로 설치한다면 package.json 설정에서 product 레벨에서 사용가능하게 된다. (--save-dev 는 개발환경시 필요)

npm install --save lodash

- dist 폴더를 추가하여 번들링된 파일을 담을 수 있도록 변경한다

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

2) 소스 수정

- lodash를 의존관리가 가능하도록 추가 했으니 소스도 변경해야 한다.

- src/index.js

+ import _ from 'lodash';
+
  function component() {
    var element = document.createElement('div');

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

    return element;
  }

  document.body.appendChild(component());

- dist/index.html

  <!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="bundle.js"></script>
   </body>
  </html>

- 기존에 추가했던 js 파일을 제거하고 bundle.js 라는 최종 번들 파일만을 참조하고 있다.

(현재는 webpack.config.js 를 설정하지 않아서 run 할 시 main.js 가 생성 될 것이다)

3) 화면 확인

npx webpack

Hash: dabab1bac2b940c1462b
Version: webpack 4.0.1
Time: 3003ms
Built at: 2018-2-26 22:42:11
    Asset      Size  Chunks             Chunk Names
bundle.js  69.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.

- npx webpack 

- npx는 node 버전 8.2 이상부터 가능하다

- 이후에 dist에 있는 html 파일을 클릭하면 해당 문구가 출력된다.(단 bundle.js 가 없으므로 main.js를 참조해야한다)


4. 설정파일 작성 - webpack.config.js

- 웹팩은 프로젝트마다 설정을 다르게 할 수 있도록 설정파일을 제공한다.

1) project

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

2) webpack.config.js

- output의 파일명이 bundle.js 로 되었다. 위에서 main.js가 생성되었다면 설정파일 이후로 bundle.js가 생성된다.

const path = require('path');

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

3. run

npx webpack --config webpack.config.js

Hash: dabab1bac2b940c1462b
Version: webpack 4.0.1
Time: 328ms
Built at: 2018-2-26 22:47:43
    Asset      Size  Chunks             Chunk Names
bundle.js  69.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.

- npx webpack --config webpack.config.js


5. npm script

- npx 커맨드를 간단하게 줄이기 위하여 NPM 커맨드를 설정한다

1) package.json

 {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "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",
      "lodash": "^4.17.5"
    }
  }

- npm run build 명령어를 npx 대신 사용 할 수 있다

npm run build

Hash: dabab1bac2b940c1462b
Version: webpack 4.0.1
Time: 323ms
Built at: 2018-2-26 22:50:25
    Asset      Size  Chunks             Chunk Names
bundle.js  69.6 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.


'Tools > webpack' 카테고리의 다른 글

[webpack] 웹팩 멀티 번들관리  (0) 2018.06.21
[webpack] 웹팩의 로더사용(webpack Loader)  (0) 2018.06.20
블로그 이미지

리딩리드

,