precondition
Every time you manually create HTML files to import packaged JS, it is obvious that this way of processing is not desirable. The ideal approach would be to generate HTML through plug-ins that automatically import the packaged JS files.
The plug-in used at this time is html-webpack-plugin.
The following are just some common usage. If you want to know more about it, you should check the official website.
"scripts": {
"webpack": "webpack"
},
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0"
}
Secondly, post the basic configuration of 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;
Finally, prepare source files.src/index.js:
console.log('console message ...');
const HtmlWebpackPlugin = require('html-webpack-plugin');
config.plugins = [
new HtmlWebpackPlugin()
];
Found, in the enddist A directory is generated.index.html,This file automatically introduces the packaged JS.
config.plugins = [
new HtmlWebpackPlugin({
template: 'template/template.html'
})
];
Self createdtemplate.html As follows:
<!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>
After packing again, it will be indist A custom template is found in the catalog.index.html。
JS” is introduced at the bottom of the page at the bottom of the page.
stayhtml-webpack-plugin You can passinject
To change the introduction position of JS:
config.plugins = [
new HtmlWebpackPlugin({
template: 'template/template.html',
inject: 'body' // Introduction at the bottom of body})]
html-webpack-plugin” variables
stayhtml-webpack-plugin
You can define many things, such astitle
、meta
And so on, these contents can be passed.htmlWebpackPlugin.options
Get it.
config.plugins = [
new HtmlWebpackPlugin({
template: 'template/template.html',
title: 'html-webpack-plugin The generated page ',Inject:'body'})]
In template file, you can passhtmlWebpackPlugin.options.title
To gettitle
Content.
<!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>
// This is the way to get all variables in html-webpack-plugin.Console.log (<% = JSON.stringify (htmlWebpackPlugin.options)%&gT;);< /script>