티스토리 뷰

javascript/webpack

webpack 강좌 4. 결과물(Output) Management

이브라히모비치 2018. 9. 9. 16:17



이전 강좌의 코드를 활용합니다.


지금까지 우리는 모든 에셋을 수동으로 index.html 에 포함시켰습니다. 하지만 어플리케이션이 커지면서 파일이름에 해시를 사용하고 여러 번들을 출력하기 시작하면, index.html 파일을 수동으로 관리하는것은 어려워 질 것입니다. 이 프로세스를 훨씬 더 쉽게 관리해주는 몇몇 플러그인이 존재하니, 알아봅시다.


준비 Preparation

먼저 프로젝트를 약간 수정해 봅시다.


project

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


src/print.js 에 몇가지 로직을 추가합니다.


src/print.js

export default function printMe() {
  console.log('I get called from print.js!');
}


그리고 src/index.js 파일에서 그 함수를 사용하십시오.


src/index.js

  import _ from 'lodash';
+ import printMe from './print.js';

  function component() {
    var element = document.createElement('div');
+   var btn = document.createElement('button');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

+   btn.innerHTML = 'Click me and check the console!';
+   btn.onclick = printMe;
+
+   element.appendChild(btn);

    return element;
  }

  document.body.appendChild(component());


또한 엔트리를 분리하는 웹팩을 준비하기위해 dist/index.html 도 수정합니다.


dist/index.html

  <!doctype html>
  <html>
    <head>
-     <title>Asset Management</title>
+     <title>Output Management</title>
+     <script src="./print.bundle.js"></script>
    </head>
    <body>
-     <script src="./bundle.js"></script>
+     <script src="./app.bundle.js"></script>
    </body>
  </html>


이제 config 를 수정합니다. 새로운 진입점entry point (print) 로 src/print.js 를 추가하고, 번들의 파일명이 entry의 이름으로 동적 생성할 수 있도록 output을 바꿔줍니다. 


webpack.config.js

  const path = require('path');

  module.exports = {
-   entry: './src/index.js',
+   entry: {
+     app: './src/index.js',
+     print: './src/print.js'
+   },
    output: {
-     filename: 'bundle.js',
+     filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };


npm run build 를 통해 무엇이 생성되는지 확인해봅시다.


Hash: aa305b0f3373c63c9051
Version: webpack 3.0.0
Time: 536ms
          Asset     Size  Chunks                    Chunk Names
  app.bundle.js   545 kB    0, 1  [emitted]  [big]  app
print.bundle.js  2.74 kB       1  [emitted]         print
   [0] ./src/print.js 84 bytes {0} {1} [built]
   [1] ./src/index.js 403 bytes {0} [built]
   [3] (webpack)/buildin/global.js 509 bytes {0} [built]
   [4] (webpack)/buildin/module.js 517 bytes {0} [built]
    + 1 hidden module


결과를 통해 웹팩은 print.bundle.jsapp.bundle.js 파일을 생성하는 것을 알 수 있습니다. 이것들은 index.html에도 선언되어 있습니다. 브라우저에서 index.html을 연 뒤 버튼을 클릭해보면 어떻게 동작하는지 확인할 수 있습니다.


그런데 만약 entry point 중 하나의 이름을 바꾸거나 추가하면 어떻게 될까요? 생성되는 번들의 이름은 바뀌겠지만, index.html에 명시된 js는 예전 파일명 그대로 일 것입니다. HtmlWebpackPlugin을 사용해서 수정해봅시다.


HtmlWebpackPlugin 설정

우선 플러그인을 설치하고 webpack.congif.js에 적용합니다.

npm install --save-dev html-webpack-plugin

webpack.config.js

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

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management'
+     })
+   ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };


빌드하기 전, 우리의 /dist폴더에 이미 index.html 파일이 존재함에도 불구하고, HtmlWebpackPlugin은 기본적으로 자체 index.html파일을 생성한다는 것에 유념해야 합니다. 즉 index.html 파일은 새로 생성된 것으로 대체됩니다. npm run build 를 실행했을때 어떤일이 벌어지는지 확인해봅시다.

Hash: 81f82697c19b5f49aebd
Version: webpack 2.6.1
Time: 854ms
           Asset       Size  Chunks                    Chunk Names
 print.bundle.js     544 kB       0  [emitted]  [big]  print
   app.bundle.js    2.81 kB       1  [emitted]         app
      index.html  249 bytes          [emitted]
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] (webpack)/buildin/module.js 517 bytes {0} [built]
   [3] ./src/index.js 172 bytes {1} [built]
   [4] multi lodash 28 bytes {0} [built]
Child html-webpack-plugin for "index.html":
       [0] ./~/lodash/lodash.js 540 kB {0} [built]
       [1] ./~/html-webpack-plugin/lib/loader.js!./~/html-webpack-plugin/default_index.ejs 538 bytes {0} [built]
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]


index.html파일을 에디터로 열어보면, HtmlWebpackPlugin이 완전히 새로운 파일을 생성하고, 자동으로 모든 번들을 추가한 것을 확인할 수 있습니다.


만약 HtmlWebpackPlugin이 제공하는 모든 기능과 옵션에 대해 더 자세히 확인하려면, HtmlWebpackPlugin repo를 읽어보십시오.


또한 디폴트 템플릿에 몇몇 추가적인 기능을 제공하는 html-webpack-template에 대해서도 확인해볼 수 있습니다.


/dist 폴더 정리 Cleaning up the /dist folder

이전 가이드와 예제 코드들로 인해 /dist 폴더는 상당히 어지럽혀졌습니다. 웹팩은 파일을 생성하고 /dist 폴더에 두지만, 프로젝트에서 실제로 사용중인지 아닌지 추적하지는 않습니다.


일반적으로 각 빌드를 수행하기전에 /dist 폴더를 정리clean해서 실제 사용된 파일만 생성하는것이 좋습니다. 어떻게 하는지 알아봅시다.


이런 것들을 다루는데 인기있는 플러그인은 clean-webpack-plugin 입니다. 설치하고 구성해봅시다.

npm install --save-dev clean-webpack-plugin

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    plugins: [
+     new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };


이제 npm run build를 실행하고 /dist 폴더를 살펴보십시오. 정상적인 동작을 했다면 오래된 파일은 없고 빌드를 통해 생성된 파일만 있을 것입니다!


명세 Manifest

어떤 파일들이 생성되어 졌는지 웹팩과 플러그인이 어떻게 “아는것” 처럼 보일까요? 모든 모듈이 어떻게 output 번들에 매핑되어 있는지 추적하는 웹팩의 manifest에 정답이 있습니다. 만약 웹팩의 output 관리 방식의 다른 방법을 알고 싶다면, manifest로 시작하는 것이 좋습니다.

  

manifest 데이터는 WebpackManifestPlugin을 통해 쉽게 사용 가능한 json으로 읽을 수 있습니다.


프로젝트에서 어떻게 이 플러그인을 사용하는지에 대한 모든 예제를 다뤄보지는 않을 것이지만, the concept pagecaching guide를 통해 장기적인 캐싱과 어떻게 관련되어 있는지 확인할 수 있습니다.


결론

HTML파일로 동적으로 번들을 추가하는 방법을 배웠습니다. 만약 좀 더 어려운 주제를 다루고 싶다면, code splitting guide를 살펴보길 권장합니다.




출처 : https://webpack.js.org/







댓글
Kakao 다음웹툰 / 웹표준 및 ft기술, 웹접근성 / 세아이 아빠, 제주 거주 중..
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday