webpack의 hmr 사용 시 멀티 파일 라우팅 하는 방법

sig03
3 min readDec 23, 2021

--

html을 여러개 만들일이 있어 webpack의 HMR 기능을 이용하기로 했다. hmr은 hot module replacement의 약자로 소스 수정 시 새로 고침을 할 필요없이 자동으로 업데이트를 해 주는 기능이다. html 만들다 보면 수정하고 브라우저에서 refresh를 무한히 반복해야 하는데 hmr 기능을 이용하면 수정 사항이 바로 반영되니 무척 편하다. 이때 webpack dev server를 사용하게 된다.

webpack을 설치하고 별도 폴더를 생성, html 파일을 만들어서 테스트 해 봤는데 브라우저에서 파일을 인식하지 못한다. 이유를 찾아보니 html webpack plugin을 추가하고 설정을 변경해 줘야 한단다.

출처 : https://www.npmjs.com/package/html-webpack-plugin

위의 방법대로 추가했다. 그러나 기본적인 루트 폴더의 index.html 파일은 hmr이 잘 동작하는데 다른 폴더의 파일은 아무리해도 안된다. 별의별 방법을 다 써봐도 안되다가 watchFiles라는 설정에 해당 폴더를 추가해주니 잘 된다. 별거 아닌데 참 신경쓰이게 만들었던…

아래는 webpack.config.js 파일이다. design 이라는 폴더에 html 파일들이 있는데 devServer 의 watchFiles 설정을 추가해줘야 hmr이 적용된다.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'none',
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
port: 9000,
watchFiles: ["./*","./design/*"],
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
}),
new HtmlWebpackPlugin({
template: './design/login.html',
filename: './design/login.html',
}),
],
};

최종적으로 index.html에서 a 태그를 걸어서 design 폴더의 html 페이지를 갈 수 있게 만들어 줬다.

--

--

sig03
sig03

No responses yet