서랍장

5. 플러그인 본문

책장/Webpack

5. 플러그인

TERAJOO 2020. 9. 27. 03:26

webpack에는 2가지의 확장 기능이 있다.

첫번째는 앞에서 배웠던 로더이고, 두번째는 플러그인이다.

로더는 우리가 가지고 있는 모듈을 최종적인 아웃풋으로 만들어가는 과정에서 사용되는 것이고, 플러그인은 그렇게 해서 만들어진 최종적인 결과물을 변형하는 것이라고 생각하면 된다.

플러그인이 더 복합적이고 자유로운 일들을 할 수 있도록 해준다는 것을 알고 있자.

플러그인은 플러그인마다 사용방법이 제각각 다르다.

때문에 다 배울필요는 없고 하나정도만 사용해보고 그 방법만 숙지하자.


webpack document에 들어가서 플러그인 탭에 들어가면 여러가지 플러그인들이 있는 것을 볼 수 있다. 그 중에서 HtmlWebpackPlugin 을 살펴보자.

코딩 과정에서 html 파일을 자동으로 생성하고 싶거나 template 화 해서 벽돌찍듯이 html 파일을 생성하고 싶을 수 있다.

이 때 저 플러그인을 쓸 수 있다.

플러그인 다운받는 방법은 다음 명령어만 치면 된다.

npm install —save-dev html-webpack-plugin

그리고 webpack.config.js 파일을 다음과 같이 바꿔준다.

// webpack.config.js 파일
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    index:'./src/index.js',
    about:"./src/about.js"
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]_bundle.js'
  },
  module:{
    rules:[
      {
        test: /\.css$/,
        use:[
          'style-loader',
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      filename:'./index.html'
    })
  ]
};

다음과 같이 config 를 만들어주게 되면 HtmlWebpackPlugin 플러그인이 index.html 을 템플릿으로 해서 html 파일이 생기게 되었고, 그 안에 다음과 같은 js, css 파일들이 번들링된 파일이 들어가 있는 것을 볼 수 있다.

// 템플릿 기준으로 만들어진 html 파일
<html>

<head>
    <link rel='stylesheet' type='text/css' src='./public/style.css'>
</head>

<body>
    <h1>Hellow, Webpack</h1>
    <div id='root'></div>
    
<script src="index_bundle.js"></script><script src="about_bundle.js"></script></body>

</html>

그런데 여전히 번들이 된 여러가지 파일들이 모두 다 들어가있는 것을 볼 수 있다. 원하는 것을 추가하기 위해서는 webpack github 들어가 다음과 같은 표를 보고 적절한 속성을 추가하면 된다. 이 떄는 chunk라는 속성을 사용하자.

NameTypeDefaultDescription
title{String}Webpack AppThe title to use for the generated HTML document
filename{String}'index.html'The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: assets/admin.html)
template{String}``webpack relative or absolute path to the template. By default it will use src/index.ejs if it exists. Please see the docs for details
templateContent{string|Function|false}falseCan be used instead of template to provide an inline template - please read the Writing Your Own Templates section
templateParameters{Boolean|Object|Function}falseAllows to overwrite the parameters used in the template - see example
inject{Boolean|String}truetrue || 'head' || 'body' || false Inject all assets into the given template or templateContent. When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element - see the inject:false example
publicPath{String|'auto'}'auto'The publicPath used for script and link tags
scriptLoading{'blocking'|'defer'}'blocking'Modern browsers support non blocking javascript loading ('defer') to improve the page startup performance.
favicon{String}``Adds the given favicon path to the output HTML
meta{Object}{}Allows to inject meta-tags. E.g. meta: {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}
base{Object|String|false}falseInject a base tag. E.g. base: "https://example.com/path/page.html
minify{Boolean|Object}true if mode is 'production', otherwise falseControls if and in what ways the output should be minified. See minification below for more details.
hash{Boolean}falseIf true then append a unique webpack compilation hash to all included scripts and CSS files. This is useful for cache busting
cache{Boolean}trueEmit the file only if it was changed
showErrors{Boolean}trueErrors details will be written into the HTML page
chunks{?}?Allows you to add only some chunks (e.g only the unit-test chunk)
chunksSortMode{String|Function}autoAllows to control how chunks should be sorted before they are included to the HTML. Allowed values are 'none' | 'auto' | 'manual' | {Function}
excludeChunks{Array.<string>}``Allows you to skip some chunks (e.g don't add the unit-test chunk)
xhtml{Boolean}falseIf true render the link tags as self-closing (XHTML compliant)

// webpack.config.js 파일
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    index:'./src/index.js',
    about:"./src/about.js"
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]_bundle.js'
  },
  module:{
    rules:[
      {
        test: /\.css$/,
        use:[
          'style-loader',
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      filename:'./index.html',
			chunk:['index']
    })
  ]
};

chunk에 위 entry 에서의 식별자를 넣어주면 된다. 그렇게 되면 해당 템플릿 기준으로 설정된 chunk 번들링만 링크되어 만들어지게 된다.

만약 두개의 html 을 만들고 싶다. 그러면 webpack.config.js 파일을 다음과 같이 변경해주면 된다.

// webpack.config.js 파일
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    index:'./src/index.js',
    about:"./src/about.js"
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]_bundle.js'
  },
  module:{
    rules:[
      {
        test: /\.css$/,
        use:[
          'style-loader',
          'css-loader',
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      filename:'./index.html',
			chunk:['index']
    }),
		new HtmlWebpackPlugin({
      template:'./src/about.html',
      filename:'./about.html',
			chunk:['about']
    }),			
  ]
};

이렇게 되면 webpack 실행시 html 파일이 2개 생기게 된다. 즉, html 도 최적화 시킬수도 있는 것이다.

이 외에도 여러가지 플러그인이 있으니 필요한 것들 잘 찾아서 사용하면 좋을 것이라 생각된다.


'책장 > Webpack' 카테고리의 다른 글

4. 로더, OUTPUT  (0) 2020.09.27
6. Webpack 참고사항  (0) 2020.09.27
3. 설정파일 도입  (0) 2020.09.27
2. Webpack 도입  (0) 2020.09.27