본문 바로가기

Bundler

[Webpack] 동적으로 HTML 생성하기 (HTMLWebpackPlugin)

Intro.

번들링 시, 만약 output파일이 여러개로 나눠지거나, 아니면 번들에 해시값을 붙여 사용하는 경우, 매번 직접 HTML파일에 새로 생성되는 파일 이름으로 경로를 고쳐주는것은 상당히 수고스럽습니다. 이러한 문제를 html파일을 동적으로 생성함으로써, 해결할 수 있습니다.

 

Goal

Before

 

After
빌드 결과

 

Method

 

1. html-loader , html-webpack-plugin을 설치합니다.

yarn add -D html-webpack-plugin html-loader

 

2. webpack config에 html 모듈을 변환 가능하겠금, html-loader를 적용시킵니다.

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

const config = {
  entry: '/src/js/index',
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader'
          }
        ]
      }
    ]
  },
  output: {
    path: path.resolve(__dirname, '../dist')
  },
};

module.exports = config;

 

3. webpack config에 html-webpack-plugin을 추가함으로써, html 모듈을 변환 시 사용할 설정을 입력합니다.

 

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

//specift entry point for module
//start from this file, when running build process
const config = {
  entry: '/src/js/index',
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader'
          }
        ]
      }
    ]
  },
  output: {
    path: path.resolve(__dirname, '../dist')
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, '../index.html') //사용할 템플릿의 경로
    })
  ]
};

module.exports = config;