Hello,

kok nae-ga ha-myun an-dweneun MAGIC...🧚

웹 프로그래밍

[ Node.js / Webpack ] 출력 관리

✿도담도담 2020. 3. 28. 17:32

1편 -  [ Node.js / Webpack ] 이번엔 웹팩 🤜

2편 -  [ Node.js / Webpack ] 자산 관리 ( css, image, font, file, loader )

관련 문서 - https://webpack.js.org/guides/output-management/

 

2편에 이어 출력관리에 대해 정리하려한다.

자산관리편을 하면서 파일을 하나 생성할때마다 import해주어야 한다면 기존과 관리면에서 어떻게 좋다는건지

의문을 가졌었는데 이번 출력관리편에서 설명을 해주겠다 :)

 

문서에서도 이와 같이 설명하고 있다.

"우리가 2편에서 수동으로 파일을 관리 했으나 시스템이 커짐에 따라 한계가 있다.

따라서 우리는 몇 가지의 플러그인을 사용해 프로세스들을 관리하려 한다. "

 


우선 /src 에 print.js를 아래의 코드로 하나 만들어 주려한다.

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

 

index.js에선 위의 print.js printMe함수를 사용하도록 코드를 변경해주었다.

( btn 부분 추가 )

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

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

	// Lodash, currently included via a script, is required for this line to work
	element.innerHTML = _.join(['Hello', 'webpack'], ' ');
	element.classList.add("hello"); // 해당 태그에 hello 클래스 추가

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

	return element;
}

document.body.appendChild(component());

 

그리고 나서 설정을 변경하여 빌드시 무엇을 생성하는지 한번 보겠다.

 

👉 webpack.config.js

const path = require('path');

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

여기서 조금 달라진 부분이 웹팩에서 파일을 읽기 시작하는 부분인 entry가 배열로 바뀌었다.

해당 설정인 경우 결과물로 여러 js파일이 만들어 질 것이다.

 

 

👉 index.js

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

 

 

이렇게 하고 실행한 결과 app.bundle.js와 print.bundle.js가 만들어 졌고,

index.js에 해당 스크립트를 둘다 import해주었으니 "Click me and check the console!" 버튼을 누르면

콘솔창에 print.js에서 만들어준 함수가 실행 되며 "I get called from ..."이라는 문구가 보여질 것이다 :)

그렇지만 아직 수동적인거 아닌가...?

 


 

드디어 위에서 설명 했듯 플러그인을 사용해보자.

문서에서는 HtmlWebpackPlugin을 요청하고있다.

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'),
      },
};

 

그리고...! 잠깐 빌드하기전에 알아야할 것이 있다.

HtmlWebpackPlugin사용시 기본적으로 /dist에 index.html을 생성하게 된다.

이뜻은 기존의 index.html이 변경된다는 말인데 이럴 경우 어떤 현상이 발생하는지 한번 보자.

빌드 후 index.html을 열어보면 자동으로 js파일을 포함시킨모습을 볼 수 있다. ( 신기해...! )

 

index.html

 


마지막으로 dist폴더를 정리하는 방법을 남기고 마무리 하도록 하겠다 :D

1, 2 그리고 3편을 진행하면서 dist폴더엔 사용하지 않는 파일들이 쌓였는데

당연한 말이게도 사용중인 파일만을 남기는게 가장 깔끔하지 않겠눈가..!

이를 관리하는 cleanup-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(),
        new HtmlWebpackPlugin({
            title: 'Output Management',
        }),
      ],
      output: {
    	filename: '[name].bundle.js',
    	path: path.resolve(__dirname, 'dist'),
      },
};

 

그리고 빌드를 한 후 dist폴더를 보니 index.html, app.bundle.js, print.bundle.js 이렇게

사용중인 세가지의 파일만 남아 있는것을 확인했다. 👏👏

 

 


 

 

3편을 해보니 이젠 index.js나 index.html에 수동으로 파일을 불러오는 코드를 작성하지 않고

webpack 설정 파일 하나로 관리할 수 있게되었다.

그런데 이미지나 스타일 시트는 어떻게 해주어야하지? 이 친구들은 2편처럼 js에 로드 시켜줘야 하는건가?

그리고 플러그인이 기본적으로 index.html을 만들어준다면 html코드는 어떻게 한단 말인가?

그래서 react를 사용하는 것인가?

아직 궁금증이 너무 많은데 일단 맨땅에 헤딩 ✍