作用
plugins 和vue的生命周期有些類似,它會在打包的某個時期幫助你完成一些事情
示例
htmlWebpackPlugin
htmlWebpackPlugin 會在打包結束后,自動生成一個html文件,并把打包生成的js文件自動引入到這個html文件中。
npm install html-webpack-plugin -D
默認
按這種方式生成的html文件內沒有任何標簽
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js'
},
plugins: [new HtmlWebpackPlugin()]
};
使用模板
src文件夾下可以新建一個index.html文件,按正常的方式書寫HTML,里面可以預先放置一些帶類名的標簽,當打包完成后,會以此文件為模板,將打包后的js文件注入。
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js'
},
plugins: [new HtmlWebpackPlugin({
template: 'src/index.html'
})]
};
CleanWebpackPlugin
CleanWebpackPlugin 會在打包開始前將制定的目錄下的文件全部清空。
npm install clean-webpack-plugin -D
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js'
},
plugins: [new HtmlWebpackPlugin({
template: 'src/index.html'
}), new CleanWebpackPlugin(['dist'])]
};
問題
CleanWebpackPlugin
插件默認根路徑是當前目錄,所以當位置文件放在build文件夾下后,插件清理的是build文件夾下的dist文件夾,而不是與build同級的dist文件夾。所以要改變插件的根路徑
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin( ['dist'], {
root: path.resolve(__dirname, '../')
})
]
output可以通過../
找到上一級
output: {
path: path.resolve(__dirname, '../dist') // 文件夾
}