參考
HtmlWebpackPlugin
在webpack
中使用HtmlWebpackPlugin
來幫助打包html
文件,并輸出一個包含所有編譯打包后的資源的HTML5
文件到dist
目錄下针炉;
配置
1.創(chuàng)建本地項目webpack-demo
mkdir webpack-demo
cd webpack-demo
2.在webpack-demo
的根目錄下創(chuàng)建package.json
文件
npm init -y
- 安裝
webpack
依賴包
npm i webpack webpack-cli webpack-dev-server --save-dev
模塊說明:
webpack
webpack
核心webpack-cli
webpack
的腳手架(啟動器)webpack-dev-server
開發(fā)環(huán)境下用于實時加載依賴
4.修改package.json
文件的scripts
屬性值,進(jìn)行打包資源的配置
"scripts": {
"dev": "webpack-dev-server --open --mode development",
"build": "webpack --mode production"
},
5.安裝插件
npm install --save-dev html-webpack-plugin
6.在webpack.config.js
文件中進(jìn)行配置
const path = require('path');
// 顯示進(jìn)程的完成進(jìn)度
var ProgressBarPlugin = require('progress-bar-webpack-plugin');
// 設(shè)置進(jìn)度字體顏色
const chalk = require('chalk');
// 以樹圖的方式展示打包后的文件
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// 輸出html
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'production',
entry: {
app: './src/app.js'
},
output: {
path: path.resolve(__dirname, '../dist'),
filename: '[name].[hash].min.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{loader: 'babel-loader'}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack Study Demo',
filename: 'index.html',//指定生成的HTML文件名
template: path.join(__dirname, './public/index.html') // 指定模板路徑
}),
new ProgressBarPlugin({
format: chalk.green('Progressing') + '[:bar]' + chalk.green(':percent') + '(:elapsed seconds)',
clear: false
}),
new BundleAnalyzerPlugin()
]
}
7.結(jié)果展示