前提說明
每次手動創建 HTML 文件來導入打包后的 JS,顯然這種處理方式是不可取的。理想的處理方式應該是通過插件生成 HTML,這個生成的 HTML 文件自動導入打包后的 JS 文件。
這個時候用到的插件是:html-webpack-plugin。
下面只是介紹一些常見的用法,如果要更深入的去了解,建議查看 官網。
前期准備
首先貼出對應的模塊 package.json:
"scripts": {
"webpack": "webpack"
},
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0"
}
其次,貼出 Webpack 的基礎配置 webpack.config.js:
const { join } = require('path');
const config = {};
config.mode = 'production';
config.entry = {
index: join(__dirname, './src/index.js')
};
config.output = {
path: join(__dirname, './dist'),
filename: '[name].bundle.js',
chunkFilename: '[name].chunk.js',
publicPath: join(__dirname, './dist/')
};
module.exports = config;
最后准備源碼文件 src/index.js:
console.log('console message ...');
配置 html-webpack-plugin
這里做一些簡單的配置,僅在 Webpack 文件中使用 html-webpack-plugin:
const HtmlWebpackPlugin = require('html-webpack-plugin');
config.plugins = [
new HtmlWebpackPlugin()
];
發現,最終在 dist 目錄中生成了一個 index.html,這個文件自動引入打包后的 JS。
自定義模板
在默認情況下使用的是默認模板,如果想自定義模板,可以使用 template
來配置:
config.plugins = [
new HtmlWebpackPlugin({
template: 'template/template.html'
})
];
自己創建的 template.html 如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
</body>
</html>
再次打包之后,會在 dist 目錄中看到使用了自定義模板的 index.html。
JS 在頁面底部引入
在 html-webpack-plugin 中,可以通過 inject
來改變 JS 的引入位置:
config.plugins = [
new HtmlWebpackPlugin({
template: 'template/template.html',
inject: 'body' // 在 body 底部引入
})
];
html-webpack-plugin 中的變量
在 html-webpack-plugin
中可以定義很多內容,比如 title
、meta
等,這些內容可以通過 htmlWebpackPlugin.options
來獲取。
config.plugins = [
new HtmlWebpackPlugin({
template: 'template/template.html',
title: 'html-webpack-plugin 生成的頁面',
inject: 'body'
})
];
在模板文件中,可以通過 htmlWebpackPlugin.options.title
來獲取 title
的內容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= htmlWebpackPlugin.options.title%></title>
</head>
<body>
</body>
</html>
<script>
// 這是獲取 html-webpack-plugin 中所有變量的方式
console.log(<%= JSON.stringify(htmlWebpackPlugin.options) %>);
</script>