[ VanillaJS ] webpack5 - HtmlWebpackPlugin
HtmlWebpackPlugin
html파일에 javascipt 번들을 자동으로 묶어주는 플러그인이다.
yarn add -D html-webpack-plugin
webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
//...
plugins: [
new HtmlWebpackPlugin({
template: "public/index.html",
}),
],
}
이제 HTML에서 script를 수동으로 추가할 필요가 없다 🎉
만약 여러 HTML을 만들고 싶다면?
webpack.config.js
const HTML_TEMPLATE = 'public/index.html';
entry: {
home: "./client/pages/home.js",
dummy: "./client/pages/dummy.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js",
},
//...
plugins: [
new HtmlWebpackPlugin({
template: HTML_TEMPLATE,
filename: "home.html",
chunks: ["home"],
}),
new HtmlWebpackPlugin({
template: HTML_TEMPLATE,
filename: "dummy.html",
chunks: ["dummy"],
}),
],
- filename 명시를 안하면 index.html 파일로 추출이 된다.
- chunks 어떤 js 번들을 script에 넣을지 결정한다.
✨ 실습
public/index.html
에서 스크립코드를 없애자.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
yarn build
아래와 같이 빌드된 것을 볼 수 있다.
dist
ㄴ home.bundle.js
ㄴ index.html
빌드된 html 파일을 보면 script이 잘 추가된 것을 볼 수 있다.
<!DOCTYPE html>
<html lang="ko">
<head>
<!-- -->
<script defer src="home.bundle.js"></script>
</head>
<!-- -->
</html>
참고로 defer는 script가 모두 로드된 후 해당 외부 스크립트가 실행됨
을 명시한다.
그냥 맨 나중에 로드한다고 생각하자..
🎉🎉
Author And Source
이 문제에 관하여([ VanillaJS ] webpack5 - HtmlWebpackPlugin), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@bepyan/VanillaJS-Webpack5-HtmlWebpackPlugin저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)