前提说明
每次手动创建 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>