webpackでhtmlをsrcからdistにコピーする
⚠結局この方法は使わず、以下の方法にした
やりたいこと
src/index.htmlをgit追跡対象にする
dist/index.htmlを生成する(git追跡対象外)
準備
$ npm install html-webpack-plugin --save-dev
srcは開発用(git追跡対象)で、distはリリース用(git追跡対象外)
code:ディレクトリ構成
.
│ .gitignore
│ package-lock.json
│ package.json
│ webpack.config.js
│
├─dist
│
├─node_modules
│ ..
│
└─src
index.html
index.js
code:.gitignore
dist
node_modules
src/index.htmlにはscriptタグを入れる必要はない(自動で付加される)
code:src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
pluginsで、開発用HTMLsrc/index.htmlを指定する
code:webpackconfig.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.html",
}),
],
};
watchモードでビルド
$ webpack --mode development --watch
dist内にbundle.jsとindex.htmlが作成される
code:ディレクトリ構成
.
├─dist
│ bundle.js
│ index.html
│
└─src
index.html
index.js
dist/index.htmlにはscriptタグが挿入されている
code:dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="bundle.js"></script></body>
</html>
参考