본문으로 바로가기

webpack vol.2 - module loader

category 개발/Webpack 2017. 9. 22. 16:31

웹팩은 번들러로써 프로젝트 작업시 사용되는 js, img, icon, font 등등을 하나의 파일로 묶어서 관리할 수가 있다.

이번엔 css를 묵는것을 알아보도록 하자.


Loading CSS

npm install --save-dev style-loader css-loader

webpack.config.js

  const path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
+   module: {
+     rules: [
+       {
+         test: /\.css$/,
+         use: [
+           'style-loader',
+           'css-loader'
+         ]
+       }
+     ]
+   }
  };

위와 같이 파일을 수정해주자.

webpack.config.js 에서의 기능은 크게 4가지로 분류된다.

entry / output / module / plugins


entry : webpack 이 bundle.js 로 묶기위한 진입점을 설정한다. 고로 이 파일에 프로젝트에 필요한 font, icon, css, js 등을 import 시키면 된다. 하지만 원래 css나 img 같은 파일들은 import가 되지 않는다. 하지만 webpack은 그것을 가능하게 한다.


output : entry를 묶어주고 난 후 결과물에 대한 설정이다. 최종 번들될 js의 이름은 무엇인지. 어느 폴더에 위치 할건지 등.


module : js 를 제외한 css, img 등은 entry 파일에 import 시킬 수 없다고 했다. 그걸 가능하게 하는 것이 module 이다. 

원하는 모듈을 설치하고 적용해보자.


plugins: 솔직히 잘 모르겠다. 이미 만들어진 module 을 가져다가 손쉽게 사용하는 정도? 

entry 파일에 import 시켜서 다른 파일을들 사용할 수 있었다면 

plugins 는 require 로 불러와서 사용가능하다. 변수에 담아서 사용하는 것이 효과적.


위의 설명을 이해했는가? 아래 소스를 분석해보면서 이해해보자.

project

  webpack-demo
  |- package.json
  |- webpack.config.js
  |- /dist
    |- bundle.js
    |- index.html
  |- /src
+   |- style.css
    |- index.js
  |- /node_modules

src/style.css

.hello {
  color: red;
}

src/index.js

  import _ from 'lodash';
+ import './style.css';

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

    // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
+   element.classList.add('hello');

    return element;
  }

  document.body.appendChild(component());


src 폴더에 style.css 파일을 생성했고 그 css 파일을 entry 파일인 index.js 에 import 시켰다. 

왜? index.js 에 모든 소스를 얹어놓고 하나의 js 파일로 묶어버리기 위해(번들링)

npm run build

Hash: 9a3abfc96300ef87880f
Version: webpack 2.6.1
Time: 834ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  560 kB       0  [emitted]  [big]  main
   [0] ./~/lodash/lodash.js 540 kB {0} [built]
   [1] ./src/style.css 1 kB {0} [built]
   [2] ./~/css-loader!./src/style.css 191 bytes {0} [built]
   [3] ./~/css-loader/lib/css-base.js 2.26 kB {0} [built]
   [4] ./~/style-loader/lib/addStyles.js 8.7 kB {0} [built]
   [5] ./~/style-loader/lib/urls.js 3.01 kB {0} [built]
   [6] (webpack)/buildin/global.js 509 bytes {0} [built]
   [7] (webpack)/buildin/module.js 517 bytes {0} [built]
   [8] ./src/index.js 351 bytes {0} [built]

성공적으로 묶였다.

index.html 파일을 브라우저에서 보면 css에 적용한 것처럼 폰트색상이 레드로 변한 것을 볼 수 있다.

즉 번들링이 잘 되었다는 뜻.


Loading image

css 를 잘 묶었으니 이제 image 파일도 entry 파일에 얹어서 묶어보자.

image 파일은 원래 entry 파일에 import 시킬 수 없으니 그걸 가능하게 하도록 loader를 설치하자.
npm install --save-dev file-loader
잘 설치가 되었는가? 
굿
그럼 아래와 같이 webpack.config.js 를 수정

webpack.config.js

  const path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader'
          ]
        },
+       {
+         test: /\.(png|svg|jpg|gif)$/,
+         use: [
+           'file-loader'
+         ]
+       }
      ]
    }
  };


새로 추가된 코드를 보면 image 파일 확장자가 있다. 

저 확장자에 해당하는 파일을 로드시켜 주겠다는 의미겠지... 

추가할 것이 있으면 추가하도록 하자.

이미지를 로드할 수 있도록 장치를 걸었으니 이미지를 넣어놓고 잘 묶이는지 볼 차례이다.


project

  webpack-demo
  |- package.json
  |- webpack.config.js
  |- /dist
    |- bundle.js
    |- index.html
  |- /src
+   |- icon.png
    |- style.css
    |- index.js
  |- /node_modules

src/index.js

  import _ from 'lodash';
  import './style.css';
+ import Icon from './icon.png';

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

    // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.classList.add('hello');

+   // Add the image to our existing div.
+   var myIcon = new Image();
+   myIcon.src = Icon;
+
+   element.appendChild(myIcon);

    return element;
  }

  document.body.appendChild(component());

src/style.css

  .hello {
    color: red;
+   background: url('./icon.png');
  }

이미지를 src 파일에 넣어놨고 진입점인 index.js 파일에 import 시켰다.

npm run build

Hash: 854865050ea3c1c7f237
Version: webpack 2.6.1
Time: 895ms
                               Asset     Size  Chunks                    Chunk Names
5c999da72346a995e7e2718865d019c8.png  11.3 kB          [emitted]
                           bundle.js   561 kB       0  [emitted]  [big]  main
   [0] ./src/icon.png 82 bytes {0} [built]
   [1] ./~/lodash/lodash.js 540 kB {0} [built]
   [2] ./src/style.css 1 kB {0} [built]
   [3] ./~/css-loader!./src/style.css 242 bytes {0} [built]
   [4] ./~/css-loader/lib/css-base.js 2.26 kB {0} [built]
   [5] ./~/style-loader/lib/addStyles.js 8.7 kB {0} [built]
   [6] ./~/style-loader/lib/urls.js 3.01 kB {0} [built]
   [7] (webpack)/buildin/global.js 509 bytes {0} [built]
   [8] (webpack)/buildin/module.js 517 bytes {0} [built]
   [9] ./src/index.js 503 bytes {0} [built]

웹팩. 번들링. 성공적.

index.html 파일을 브라우저에서 보면 이미지가 보일 것이다. 우왕 굿.




오늘은 여기까지, 다음포스팅은?

css와 image 파일을 번들하는 법을 배웠다. 

다음엔 font 파일.



'개발 > Webpack' 카테고리의 다른 글

Getting Started  (0) 2017.09.22
webpack-dev-server 셋팅  (0) 2017.09.19
package.json - scripts  (0) 2017.09.19
npm intall webpack --save-dev  (0) 2017.09.19