본문 바로가기

프레임워크/Webpack

웹팩 배우기 1

웹팩 배우기 1

참고자료 Understanding the Modern Web Stack: Webpack - The Basics (link)

What is webpack?

  • a bundler for javascript applications

Get started

  • install node; do it yourself

  • start a npm project

      npm init -y
  • create two files

    • index.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Document</title>
          <script src="node_modules/lodash/lodash.min.js"></script>
          <script src="script.js" defer></script>
      </head>
      <body></body>
      </html>
    • script.js with respect to where index.html is

      function component () {
       const element = document.createElement('div');
      
       element.innerHTML = _.join(['Hello', 'webpack'], ' ');
      
       return element;
      }
      
      document.body.appendChild(component());
  • install lodash

      npm install lodash
  • index.html을 브라우저로 열면 Hello webpack 이 보인다. 이제 webpack을 이용해서 html을 로딩해보자. 먼저 src 폴더를 만들고 index.htmlscript.js를 옮긴다.

  • install webpack

      npm install webpack webpack-cli --save-dev
  • create webpack config file webpack.config.js

      const path = require("path");
    
      module.exports = {
          mode: "none",
          entry: "./src/script.js",
          output: {
              filename: "main.js",
              path: path.resolve(__dirname, "dist")
          }
      }
  • 그리고 webpack 를 실행하면

      npx webpack
  • webpack.config.jsentryoutput에 적은 대로 script.js 을 entry 포인트로 시작해서 webpack이 번들링을 하여 main.js 을 생성시킨다.

      .
      ├── dist
      │   └── main.js
    
  • 하지만 index.html 여전히 script.js 를 가르키고 있는 상황 따라서 HtmlWebpackPlugin을 사용하여 해결한다.

      npm install html-webpack-plugin --save-dev
  • update webpack.config.js

      const path = require("path");
      const HtmlWebpackPlugin = require("html-webpack-plugin") ;
    
      module.exports = {
          mode: "none",
          entry: "./src/script.js",
          output: {
              filename: "main.js",
              path: path.resolve(__dirname, "dist")
          },
          plugins: [
               new HtmlWebpackPlugin({
                   filename: "index.html",
                   template: "./src/index.html",
               }),
          ],
      }
  • after this, we need to remove two lines of <script> tag from html and run npx webpack. and there you go we have index.html in dist folder and <scrip> tag for main.js is added therein by webpack

      .
      ├── dist
      │   ├── index.html
      │   └── main.js
    
  • 하지만 index.html을 로딩해보면 에러가 나는데 lodash 때문이다. script.js에 다음을 추가해주면 해결된다.

// script.js
import _ from 'lodash';
  • 하지만 또다른 문제는 lodash 팩키지 전체를 import 해왔기 때문에 번들 파일 main.js의 크기가 필요이상을 크다는 것.
  • 해결 방법은 script.js 에서 사용하는 모듈만 import 해오는것
    // before
    import _ from 'lodash';
    

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

// after
import join from 'lodash/join';

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